#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
float x=1234.56;
printf("%10f\n", x);
return 0;
}
Why does x change value, shouldn't be 1234.560000. It displays 1234.560059
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
float x=1234.56;
printf("%10f\n", x);
return 0;
}
Why does x change value, shouldn't be 1234.560000. It displays 1234.560059
There's only so many values that can be represented exactly as a float
, and 1234.56 ain't one of them:
public class WhatsTheFloatingPoint
{
public static void main(String[] args)
{
float x = 1234.56f;
BigDecimal y = new BigDecimal(x);
System.out.println(y);
}
}
This program prints the closest value that is actually used: 1234.56005859375
Its value is always:
1234.560059...
when you show fewer digits, it will round off the tiny extra amount required to map into binary fractions
That is why floating point equivalence is generally done with some acceptable epsilon, or tiny difference.
Note that the amount off can vary by architecture and compiler options