0

I have to calculate a fairly complex formula in my code, and I'm wondering how to decide whether I should use BigDecimal or just double to do it.

The function is is:

f(x) = 1.03^(4 - ((1/3) * (x-9)^2))

where x is a double rounded to 4 decimal points, e.g. 1.2345

what are the pros and cons of using BigDecimal versus double and how much precision might I lose if I use double to represent everything?

jcm
  • 5,499
  • 11
  • 49
  • 78
  • if you care about the 15th digit or so.. http://stackoverflow.com/questions/13542944/how-many-significant-digits-have-floats-and-doubles-in-java – zapl Mar 09 '16 at 23:20
  • 2
    There are too many variables for there to be one specific answer. Do you care about more than 15 significant digits precision (not 15 decimal places, 15 _total_ digits)? If no, then `double` is probably fine as long as you recognize that many "common" numbers cannot be exactly represented as floating point. [This is required reading](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jim Garrison Mar 09 '16 at 23:22

2 Answers2

1

The main pro of using BigDecimal over double is that the first one can achieve more precision over a fixed number of decimals. The main con is that BigDecimal requires more cpu operations to make same calculations.

About precision of the two, if you take the old same example of monetary value (i'm from Europe, then Euros), you can immeditely see that 0,009€ or less simply doesn't make any sense while the minimum unit is 0,01€. This is a fixed precision value and BigDecimal is good to manage it.

If the calculation of your question is about something that needs a sufficiently good precision (or average good precision as Jonah said) and doesn't have a well defined minimum unit, that can be a floating point value.

0

A double can store 16 significant figures accurately on average. I don't think using a double in that formula will result in significant data loss. However, if speed is not a concern at all then using BigDecimal would be my choice. See How many significant digits have floats and doubles in java?

Community
  • 1
  • 1
Jonah Haney
  • 521
  • 3
  • 12