different values for float and double

前端 未结 5 514
独厮守ぢ
独厮守ぢ 2021-01-08 01:16

I don\'t understand why are float values different from double values. From the example bellow it appears that float provides different result than double for the same opera

相关标签:
5条回答
  • 2021-01-08 01:33

    Doubles have twice the precision of floats. Thus they have smaller rounding errors.

    A float has (usually) 32 bits, and a double 64 (again usually). Thus floats have rounding errors on more numbers than doubles.

    0 讨论(0)
  • 2021-01-08 01:35

    A float is a 32 bit IEEE 754 floating point.

    A double is a 64 bit IEEE 754 floating point.

    so it is just a matter of precision because neither of the fraction portions .8 and .65 have a terminating binary representation, so there is some rounding error. the double has more precision so it has slightly less rounding error.

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    0 讨论(0)
  • 2021-01-08 01:38

    Can you explain what makes this difference between float and double?

    Sure. Imagine you had two decimal types, one with five significant digits, and one with ten.

    What value would you use to represent pi for each of those types? In both cases you'd be trying to get as close to a number which you couldn't represent exactly - but you wouldn't end up with the same value, would you?

    It's the same for float and double - both are binary floating point types, but double has more precision than float.

    0 讨论(0)
  • 2021-01-08 01:41

    Floats have less precision than doubles.

    It's roughly half as much - 23 bits vs 52 for double(Thanks a lot Mr. Skeet!)!

    32-bit for floats, 64-bit for doubles. ...Remember that the word "float" has fewer letters than "double", that's a "memory" trick :)

    0 讨论(0)
  • 2021-01-08 01:45
    public class Main {
    
        public static void main(String[] args) {
            float  a=12.6664287277627762f;
            double b=12.6664287277627762;
    
            System.out.println(a);
            System.out.println(b);
        }
    }
    

    Output:

    12.666429
    12.666428727762776
    

    float can handle about 7 decimal places. A double can handle about 16 decimal places.

    0 讨论(0)
提交回复
热议问题