Friday 29 January 2016

Julia: Represent Big float values


BigFloat(x) is used to create an arbitrary precision floating point number.
julia> BigFloat(1.1)
1.100000000000000088817841970012523233890533447265625000000000000000000000000000

As you observe above snippet, 1.1 is converted to 1.100000000000000088817841970012523233890533447265625000000000000000000000000000, it is because decimal literals are converted to floating point numbers when parsed. So it won’t give actual result.

Convert string to BigFloat
By using parse method a string can be converted to BigFloat.

parse(type, str[, base])
Argument
Description
type
Represents the type to convert. Default base is 10.
str
String to convert. If string is not valid number, then error is raised.
base
Base is optional, for integer conversion default to 10.


julia> x=parse(BigFloat, "2.1")
2.099999999999999999999999999999999999999999999999999999999999999999999999999986


Convert string literal to BigFloat
By Using ‘big’ string literal, we can convert a string literal to BigFloat.

julia> big"2.1"
2.099999999999999999999999999999999999999999999999999999999999999999999999999986


Setting precision for BigFloat
You can set the precision for BigFloat number using ‘set_bigfloat_precision(x::Int64)’ method. ‘get_bigfloat_precision()’ method return the number of bits used for BigFloat arithmetic.

julia> set_bigfloat_precision(20)
20

julia> x=big"2.1"
2.0999985

julia> y=BigFloat(1.1)
1.1000004

julia> x+y
3.1999969

julia> get_bigfloat_precision()
20


You can change the precision for particular block of code using ‘with_bigfloat_precision(f::Function, precision::Integer)’.

julia> with_bigfloat_precision(20) do

           BigFloat(1) + parse(BigFloat, "0.0001")

       end
1.0000992






Previous                                                 Next                                                 Home

No comments:

Post a Comment