why condition become true in if/esle ?
1 回表示 (過去 30 日間)
古いコメントを表示
Hi, the below simple code is making trouble that : here Vxp and Vxn both are same value(32.000); so the difference must be 0 but here program still enter in if condition. instead it should enter in else condition. why it's happening ? anyone have the idea what cause make condition false ? even I check values by insterting break point. however same code in another matlab function block is running fine. could anyone help in this regard ?
for kbit = 1:Nbit
if Vxp - Vxn > 0
B(kbit) = 1;
Vxp = Vxp - Vref*2^(-kbit);
else
B(kbit) = 0;
Vxn = Vxn - Vref*2^(-kbit);
end
end
Thanks
0 件のコメント
採用された回答
madhan ravi
2018 年 11 月 13 日
編集済み: madhan ravi
2018 年 11 月 13 日
see https://www.mathworks.com/matlabcentral/answers/429435-matlab-value-error-while-creating-vector#answer_346543 for explanation
if abs(Vxp-Vxn)<1e-4
6 件のコメント
その他の回答 (1 件)
Stephen23
2018 年 11 月 13 日
編集済み: Stephen23
2018 年 11 月 13 日
"...here Vxp and Vxn both are same value(32.000); so the difference must be 0..."
Evidently not true.
"why it's happening ? anyone have the idea what cause make condition false ?"
Sure, read these:
This is worth reading as well:
All programmers need to understand that calculations on floating point numbers can accumulate floating point errors (like your example does), and do not expect floating point mathematics to be equivalent to the symbolic maths that they learned in high school (e.g. operations on floating point values are not commutative). They write their code accordingly, by comparing the difference of floating point values against a tolerance:
abs(A-B)<tol
5 件のコメント
Stephen23
2018 年 11 月 13 日
編集済み: Stephen23
2018 年 11 月 13 日
@Sarfaraz Ahmed: your code has a few interesting features, e.g.:
- you have an Nbit variable to select the number of ADC bits, but then you hardcoded B(7), B(6), etc. So when I tried your code with Nbits=4, it threw an error.
- you enlarge B on each loop iteration. It would be more efficient to preallocate this before the loop.
- No code comments, no help, no input/outut specifications, not description, no named algorithm.
I am not completely sure what your algorithm is. Can you please give a link that explains the algorithm you are trying to implement.
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!