Recently i tested following program & i was expecting runtime error but it shows "nan" as output. Why & How? I am using g++ compiler.
#include <iostream>
int main()
{
float f=0.0f/0.0f;
std::cout<<f;
return 0;
}
Same way i also tried similar type of program in Java & C# & it shows again "nan" as output.
class Test
{
public static void main(String args[])
{
float f=0.0f/0.0f;
System.out.println(f);
}
}
class Test
{
public static void Main(string[] args)
{
float f=0.0f/0.0f;
Console.Write(f);
}
}
I want to know that how floating point arithmetic is implemented & how it differes from integer arithmetic. Is it undefined behaviour in case of C++? If yes, why? Please help me.
nan
stands for not a number. Dividing by the integer 0 is always a mistake, because you cannot divide by 0 in mathematics. Therefore many languages throw an exception when you divide by the integer 0.
It would be less reasonable to do this with floating point numbers because floating point calculations are not exact. For example, a calculation could result in 0.0f
because 0.0f
is the closest floating point value to the answer, not because the true value of the answer is mathematically 0. Therefore trying to divide by the floating point value 0.0f
might not be a consequence of an incorrect algorithm. nan
essentially means that the answer to your calculation could not be determined because it involved the division of two numbers so small it was impossible for the computer to distinguish them from 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With