nagfer
April 16, 2023, 1:14pm
1
Hi Guys,
I have a similar mathematical form in my code:
float S = 0.0;
float R = 0.0;
float F = 0.0;
S = (1 + (sqrt(R/F))) / (1 - (sqrt(R/F)));
Serial.println("Calculation");
Serial.println(S);
Why do I get "nan" result in the serial monitor, instead of a valid number, even it is 0.0?
nagfer:
R/F
The result is undefined by 0/0.
nagfer
April 16, 2023, 1:20pm
3
It is clear, but if I put this form to a calculator, 0/0 results 0.
Is there any opportunity to I force the code to process with 0/0, and get 0 as result?
If so, the result of the calculator must be 1, 0 divided by 0 must be 1 and not zero.
Maybe your calculator is faulty.
(Mine says "Error")
2 Likes
The Windows 11 native calculator says, "Result is undefined".
srnet
April 16, 2023, 1:27pm
8
Maybe it should say "nan" ?
I would be okay with that.
There isn't a unique solution when you divide anything by 0, there are two results +∞ and -∞.
The calculator is wrong.
Is there any opportunity to I force the code to process with 0/0, and get 0 as result?
Even if you use a very small number close to zero you don't get zero as an answer:
0.00000000001/0.00000000001 = 1
Yes, well almost, you can check the value before you perform the division, in an 'if' statement.
if (F != 0)
S = (1 + (sqrt(R/F))) / (1 - (sqrt(R/F)));
else
S = 0;
However, it's mathematically unsound as has been pointed out.
nagfer
April 16, 2023, 1:33pm
12
Yes, true, I said stupid thing Sorry, my calculator also says not defined
Idea: In case of the result is not valid, I need a value 0.0 in the variable "S".
After the form (calculation) is finalized, can I say something similar?
If (value of S = nan) {S = 0.0}
if Yes, how should I code it?
Why not simply check first to see if the divider is zero?
Hello nagfer
Take some time read and study to gain the knowledge.
https://cplusplus.com/reference/cmath/isnan/
Have a nice day and enjoy coding in C++.
nagfer
April 16, 2023, 1:45pm
15
You are right. These floats are coming from a coversion of voltages from Analog inputs, where both can be 0V, or at least one of them can be 0V. Both are valid states, but the first state can cause confusion in the mathematical form.
Based on your idea it is working. Thanks!
if (F == 0 && R == 0){S = 0.0;}
else { float S = (1 + (sqrt(R/F))) / (1 - (sqrt(R/F))); }
You don't need to check R. Zero divided by anything is still zero.
nagfer
April 16, 2023, 1:51pm
17
I have to check it, because if {F == 0} is fulfilled but in the same time R = 5V, I do not want to init S = 0.0;
Perhaps you can reformulate to avoid the singularity.
The whole thing is very "sus".
xfpd
April 16, 2023, 6:26pm
20
anon56112670:
divider
"divisor" (dividend/divisor=quotient)... <3 : ) <3