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
更多回答(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!