why condition become true in if/esle ?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sarfaraz Ahmed
le 13 Nov 2018
Commenté : Sarfaraz Ahmed
le 13 Nov 2018
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 commentaires
Réponse acceptée
madhan ravi
le 13 Nov 2018
Modifié(e) : madhan ravi
le 13 Nov 2018
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 commentaires
Plus de réponses (1)
Stephen23
le 13 Nov 2018
Modifié(e) : Stephen23
le 13 Nov 2018
"...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 commentaires
Stephen23
le 13 Nov 2018
Modifié(e) : Stephen23
le 13 Nov 2018
@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.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!