English 中文(简体)
Converting representation from decimal to floating point numbers - pitfalls
原标题:

I m working on some functionality in a financial application. All numbers are represented as decimals without rounding errors both in the code and in the database. However, I m having some performance problems and I m considering switching to floating point numbers (float/double) in my own computations. This is based on the assumption that rounding error isn t a problem (which I will have to check with the customer).

However, I would like to know what pitfals there are if I do this conversion. Are there a type of expression that when computed using floating point numbers may differ significantly from the same expression computed using decimals?

问题回答

The problem with using floats is that you ll end up with (possibly) unexpected precision issues.

If you use float then the max value you can represent properly will be $167,772.16. If you use double then the max value will be better (about $180 trillion).

Have you considered using a straight int or long (32-bit or 64-bit) representing $0.01 intervals? That way you can control the values much better but the performance should be good. You can also wrap them in a struct to make it easier to use with standard math operators.

A financial application is usually the number one example of when not to use floating point. So beware.

Anyway, this article has more than you ll ever want to know about floating point. It s mostly about the D programming language, but it has a lot of generally useful stuff to know.





相关问题
Haskell minimum/maximum Double Constant

Is there any way in Haskell to get the constant that is the largest and smallest possible positive rational number greater than zero that can be represented by doubles?

integer automatically converting to double but not float

I have a function like below: void add(int&,float&,float&); and when I call: add(1,30,30) it does not compile. add(1,30.0,30.0) also does not compile. It seems that in both cases, it ...

Lower Bounds For Floating Points

Are there any lower bounds for floating point types in C? Like there are lower bounds for integral types (int being at least 16 bits)?

Floating point again

Yesterday I asked a floating point question, and I have another one. I am doing some computations where I use the results of the math.h (C language) sine, cosine and tangent functions. One of the ...

热门标签