1

I have to implement some relatively complex formulas in a Java application. The inputs to these formulas are include up to 30 or so variables. Some of these variables in their natural form are integers, some are reals with a precision of around 3 to 4 decimal places. I am using commons-math for the functions, but I am wondering about precision and convenience:

Would it be best to convert all variables integers to Double prior to passing to the formula methods. This way there is a consistency within the formulas and secondly can I safely use Double for 3 to 4 dp precision? Is there a "best practice" for implementing complex math in Java?

skyman
  • 2,255
  • 4
  • 32
  • 55
  • 1
    In general, using ints and doubles together in math in java will "promote" the int to a double, so no loss of precision occurs. – kevinsa5 Sep 03 '15 at 03:18
  • @kevinsa5 Is this true of Integer and Double? Should I be using int and double? – skyman Sep 03 '15 at 03:20
  • Integer and Double are when you need formal classes -- for normal math operations, int and double are standard. They usually get converted between each other when necessary anyway. See "autoboxing" with java. – kevinsa5 Sep 03 '15 at 03:27

2 Answers2

1

There is no need to convert variables Integers to Double. Initialize all the variables as Double because if you are having a part in formula where it is just dividing 2 Integers and is added to the result of 30 variables, then it will lose the values for decimal places. So it best to use Double for mathematical purposes where Decimal places are significant to produce a correct answer.

burglarhobbit
  • 1,860
  • 2
  • 17
  • 32
0

For floating point calculation with precission... I would suggest to use BigDecimal. Because Double and Float are know for their lost of precision. The following snippets illustrates the problem.

System.out.println( 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f );
System.out.println( 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d );

1.0000001
0.9999999999999999

Multiplying 0.1 ten times, you expect to get 1. But its not.

Ferdinand Neman
  • 680
  • 3
  • 6
  • 1
    +1, This problem is not related Java. Floating point implementations are hardware based and follows IEEE standard. So, native floating point values and precision losses, or BigDecimal and performance losses ... –  Sep 03 '15 at 03:56