Using BigDecimal and double
-
Upload
peter-lawrey -
Category
Technology
-
view
903 -
download
2
description
Transcript of Using BigDecimal and double
(c) Higher Frequency Trading
Using BigDecimal and double
Using BigDecimal and double(Or why you can use double for money)
Higher Frequency Trading(c) Peter Lawrey
(c) Higher Frequency Trading
Nearest representable value
Floating point numbers are represented using a sum of powers of two e.g. 9.75 = 8 + 1 + 0.5 + 0.25
Values like 0.1 cannot be exactly represented using floating point but when you print it, it “knows” to print the simplest number which would be represented at this value.
(c) Higher Frequency Trading
Rounding a double
Why do we get errors with double
– Representation errors, • 0.1 is not exactly 0.1
• new BigDecimal(0.1)– Using BigDecimal.valueOf(0.1) instead.
– Rounding errors, • each calculation gives the closest match
(c) Higher Frequency Trading
Rounding a double
Rounding errors are not random errors. You can predict that the error will be less than 1 ulp.
If you display a number with such as error it will have a sane toString()
However, if you perform a calculation on a value which cannot be exactly represented, you will see the error.
(c) Higher Frequency Trading
Rounding a double
Ways to round to significant digits
public static double round2(double d) {
return Math.round(d * 1e2) / 1e2;
}
(c) Higher Frequency Trading
OpenHFT Java-Lang /**
* Performs a round which is accurate to within 1 ulp.
* i.e. for values very close to 0.5 it might be rounded up or down.
* This is a pragmatic choice for performance reasons as it is assumed you are not working on the edge of the precision of double.
*/
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ?
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor : d;
}
(c) Higher Frequency Trading
Errors and doubleExercise 10 mins Use BigDecimal to print the actual value of 0.1 Print the values of x for
for(double d = 0.0; d != 1.0; d += 0.1)
Print the values of x for
for(int x = 0; x != 10; x++) {
double d = x * 0.1;
Print the values of x for
for(int x = 0; x != 10; x++) {
double d = x / 10.0;
(c) Higher Frequency Trading
BigDecimal or double
Exercise 20 mins. Write a loop to take the mid price of 1000 bid
and ask values as BigDecimal and double. Use randomly generated prices.
– What sort of distribution should your use? Test the mid values are the same. How long does each take? Why?
(c) Higher Frequency Trading
rounding double
Exercise 20 mins. Write a function for rounding a double
– Using Math.round
– Using / of whole numbers Compare the result with BigDecimal. Can this be written without Math.round? Is this any faster?