C# float bug? 0.1 - 0.1 = 1.490116E-08

后端 未结 5 564
自闭症患者
自闭症患者 2020-12-03 16:23

What\'s going on?! Subtraction works fine until I get to 0.1 - 0.1. I\'m in visual c# 2008 using the nonoba.com API.

Console.WriteLine(\"hit! \" + Users[targ         


        
相关标签:
5条回答
  • 2020-12-03 17:02

    Slighly offtopic, but here's an interesting read that describes why cos(x) != cos(y) can be true even if x == y:

    http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18

    0 讨论(0)
  • 2020-12-03 17:05

    If you're always adding and subtracting "nice round" numbers, that is tenths or hundredths, then you can keep track of your hit and health values in integer tenths-of-units. An analogy is a financial program that keeps track of money in integer cents, instead of floating point dollars. Using integers avoids all the problems of floating point math.

    0 讨论(0)
  • 2020-12-03 17:05

    Floating point math is always approximate, in any language, because that's how CPUs work. If you care about the absolute precision of your answers - for example, because you're dealing with money - then you shouldn't use floating point.

    0 讨论(0)
  • 2020-12-03 17:22

    You obviously need to read "What Every Computer Scientist Should Know About Floating Point Numbers".

    Instead of thinking that I've found a bug in situations like this, I usually assume that one of my assumptions needs checking first.

    0 讨论(0)
  • 2020-12-03 17:25

    That seems pretty normal for floating point math... you always have to check against a small delta to account for imperceptible rounding differences. Depending on the scenario, decimal might be what you want.

    Basically, unless you can be sure that it is exactly the same 0.1 in both cases (i.e. nothing has been done to them), you aren't likely to get zero; in general you'll get something very nearly zero. With decimal you'll usually get more what you expect intuitively.

    See also Jon Skeet's pages here:

    • Binary floating point
    • Decimal floating point
    0 讨论(0)
提交回复
热议问题