Shravan
Shravan

Reputation: 2918

Why does this float operation in C++ and Java give different results?

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;

Upvotes: 3

Views: 669

Answers (3)

5gon12eder
5gon12eder

Reputation: 25459

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.

Upvotes: 4

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

Decide your precision level, and specifically set that for the output stream, that should show same

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149195

In IEEE floating point representation, neither 0.1 nor 0.2 (nor 0.3) are exact values. Only negative power of 2 and their combinations would be (0.5, 0.25, 0.75 for example ...).

So the differences that you see are only differences in the default output formatting as stated by Matt Adams.

Upvotes: 2

Related Questions