简体   繁体   中英

Confusion in floating-point modulus

I know C++ very well, but am a beginner in java.

Here are two tested programs:

The Java program gives output 3.2999997

import java.util.*;
import java.lang.*;
import java.io.*;

class Test
{
    public static void main(String args[])
    {
       float f = 9.9f, m = 3.3f;
       float c = f % m;
       System.out.println(c);
    }
}

The C++ program gives output 8.88178e-16

#include <iostream>
#include<math.h>
int main()
{
   float f = 9.9f, m = 3.3f; 
   std::cout << fmod (9.9,3.3);
   return 0;
}

I am satisfied with the C++ program's output, but why is Java not giving an answer around zero?

How is this possible, since 3.3 * 3 = 9.9

I know Java considers float's precision as 6-7 decimal digits, but I do not know how this output came? I researched this question on web, but did not find the logic behind this.

The Java program is using float s. But the C++ program is declaring float s and using what I assume are double floating point literals.

In your Java program I get 3.2999997 also, but when I change to double s, the output matches your C++ program's output: 8.881784197001252E-16 ( demo ).

Either way, you're off from the true mathematical value of 0 because of floating-point numbers in both languages can be inexact. The float values must be a little more inaccurate because they are more imprecise, hence a different value, a little less than 3.3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM