c# float [] average loses accuracy

后端 未结 3 1549
遇见更好的自我
遇见更好的自我 2021-01-21 08:01

I am trying to calculate average for an array of floats. I need to use indices because this is inside a binary search so the top and bottom will move. (Big picture we are trying

3条回答
  •  走了就别回头了
    2021-01-21 08:51

    Just to add to the conversation, be careful when using Floating point primitives.

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Internally floating point numbers store additional least significant bits that are not reflected in the displayed value (aka: Guard Bits or Guard Digits). They are, however, utilized when performing mathematical operations and equality checks. One common result is that a variable containing 0f is not always zero. When accumulating floating point values this can also lead to precision errors.

    Use Decimal for your accumulator:

    1. Will not have rounding errors due to Guard Digits
    2. Is a 128bit data type (less likely to exceed Max Value in your accumulator).

    For more info: What is the difference between Decimal, Float and Double in C#?

提交回复
热议问题