I just came across this website and tried doing that in Java and C++. Why writing the following in Java gives 0.30000000000000004
double x = 0.1 + 0.2;
System.out.print(x);
Whereas writing the following in C++ gives 0.3?
double x = 0.1 + 0.2;
cout<<x;
There is no guarantee from the C++ standard that IEEE 754 floating point arithmetic is used, so the result is actually implementation defined. However, most implementations will do it.
In Java, float and double are defined to be IEEE 754 floating point types. In addition, you can add the strictfp modifier to a class or method declaration to require strict IEEE 754 floating point arithmetic be used even for intermediary results.
When dealing with floating point numbers, in case of doubt, it is often useful to look at the actual bit representation.
#include <cstdint>
#include <cstdio>
int
main()
{
static_assert(sizeof(double) == sizeof(uint64_t), "wrong bit sizes");
const double x = 0.1 + 0.2;
const uint64_t bits = *reinterpret_cast<const uint64_t *>(&x);
printf("C++: 0x%016lX\n", bits);
return 0;
}
public final class Main {
public static void main(final String[] args) {
final double x = 0.1 + 0.2;
final long bits = Double.doubleToLongBits(x);
System.out.printf("Java: 0x%016X\n", bits);
}
}
When I execute both programs on my computer (GNU/Linux with GCC and OpenJDK), the output is
C++: 0x3FD3333333333334
Java: 0x3FD3333333333334
which shows that both yield the exact same result. However, a portable program should not rely on this.
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