Precision lost in float value using java

后端 未结 5 1115
醉酒成梦
醉酒成梦 2020-12-03 16:15

Given below the test code and its output. When I get float value from number value, precision is lost.. Can anyone tell me why this behaviour and also how to handle this?

5条回答
  •  隐瞒了意图╮
    2020-12-03 16:53

    I love these. But I'll make it quick and painless.

    Floats and decimals (aka floating points) aren't kept in the memory precisely either. But I don't want to get into float accuracy vs precision issues here, i'll just point you to a link - http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

    As far as your other question, lemme put it this way, since floats are stored in scientific notation.

    floatVal = 6.765432E6 = 6.7 * 10^6
    MAX_VALUE = 3.4E38 = 3.4 * 10^38
    

    MAX_VALUE is 32 orders of magnitude bigger than your float number. Feel free to take a look at here as well http://steve.hollasch.net/cgindex/coding/ieeefloat.html

    I've spent a great deal of time comparing and fixing some FP issues a few months ago...

    Try to use a small delta when comparing floats. Maybe this link will help you http://introcs.cs.princeton.edu/java/91float/

提交回复
热议问题