Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact decimal arithmetic in Julia

Due to the nature of floating-point math, .4 * .4 = 0.16000000000000003 in Julia. I want to get the mathematically correct answer of 0.16, in a CPU-efficient way. I know round() works, but that requires prior knowledge of the number of decimal places the answer occupies, so it isn't a general solution.

like image 946
James Beezho Avatar asked May 15 '15 16:05

James Beezho


People also ask

What is Float64 in Julia?

The standard choice for floating-point values is Float64 , which is double precision using 64 binary bits. bitstring(1.0) "0011111111110000000000000000000000000000000000000000000000000000" The first bit determines the sign of the number: [bitstring(1.0); bitstring(-1.0)]

How do you round a number in Julia?

Getting rounded value of a number in Julia – round() Method The default round process is done to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer. The specified value x is rounded to an integer value and returns a value of the given type T or of the same type of x.

How is a float defined in Julia?

Literal Float32 values can be entered by writing an f in place of e : julia> x = 0.5f0 0.5f0 julia> typeof(x) Float32 julia> 2.5f-4 0.00025f0. Values can be converted to Float32 easily: julia> x = Float32(-1.5) -1.5f0 julia> typeof(x) Float32.


1 Answers

Some options:

  1. Use the inbuilt Rational type. The most accurate and fastest way would be

    16//100 * 16//100

If you're using very big numbers these might overflow, in which case you can use BigInts instead,

big(16)//big(100) * big(16)//big(100)

(you don't actually need to wrap them all in bigs, as the rationals will promote automatically).

You can also use rationalize(0.16), but this may not be quite as accurate or efficient, as the literal 0.16 has already been converted to a Float64 by the time Julia sees it, so you're converting to a binary floating point and then to a Rational.

  1. DecFP.jl wraps the Intel implementation of IEEE-754 Decimal floating point. This should be reasonably fast (though not as efficient as binary), but has fixed precision, so you will have to round at some point.

  2. Decimals.jl is a "big decimal" floating point library: as it uses arbitrary precision arithmetic, it is going to be slower than DecFP.

To say which is the best would require more information about your intended use.

like image 87
Simon Byrne Avatar answered Sep 30 '22 14:09

Simon Byrne