daino3
daino3

Reputation: 4566

Why/when to use floats instead of BigDecimal

This might be a naive or loaded question, but after suffering through debugging floating point number issues, I have a question to ask:

If there are rounding issues with floats because of the whole base 2 vs. base 10 representation difference between floats and bigdecimals… why/when would you use floats vs. bigdecimals?

Almost all major programming languages have a BigDecimal library... soo

It seems to me that accuracy in math trumps any sort of performance bump you’d get by using floats….. so why hasn’t the software world just abandoned floats and said, “sorry, we’re going all-in on BigDecimal”?

Upvotes: 2

Views: 425

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The key question is whether your application would benefit from exact representation of terminating decimal fractions.

Being able to represent numbers such as 1.01 exactly is very, very useful in financial calculations.

On the other hand, when you are dealing with physical measurements the decimal result is itself just an approximation. I do not believe any physical quantity has been measured to the precision of IEEE 754 64-bit float, the commonest implementation of doubles.

There is a misconception that BigDecimal libraries remove rounding issues. They only help with numbers that are exactly representable as reasonably short decimal fractions. BigDecimal does no better than double at representing one third.

Upvotes: 4

GhostCat
GhostCat

Reputation: 140427

Assume you that you are collecting a huge set of measurement data. You know that your sensors give you an error rate of say 5% already. Why would you want to spend a lot of additional computing power to achieve 100% correct computations on that data?! And lets say, we are not talking about 10 MB of data; but 10 TB. Or Petabyte. Are you still convinced that it is worth using BigDecimal to process that data?

In other words: there are many occasions where you absolutely do not need that 100% of correctness. And then you are not willing to pay the price tag associated with that 100%.

I fully agree: as soon as we are talking about numbers that represent currency for example, we do whatever we can to avoid rounding errors. But we simply do not need to treat all data the same. Because in the real world, there are many different requirements; and good engineering is about picking that tool that provides the optimal solution given such constraints.

Upvotes: 2

Related Questions