in matlab we can change datatype by double(22/7), is there any method in julia.
Thank You
22/7
is already “double” in Julia, it’s called Float64
julia> 22/7
3.142857142857143
julia> typeof(ans)
Float64
It is not entirely clear what you mean: in Julia 22/7 will evaluate to a Float64 (a double in c). You can convert to other types by calling their constructor. For example Float32(22/7) would yield a single precision floating point value. Does that answer your question?
It is not perfectly clear what you want to achieve, because the usage of double
in your example in Matlab does not really do much:
>> 22/7
ans =
3.1429
>> class(ans)
ans =
'double'
>> double(22/7)
ans =
3.1429
>> class(ans)
ans =
'double'
As the others have said, in this specific example, the object is already Float64, aka C-double.
In general to cast an object to be of a different tye use objTypeT = convert(T,objToConvert)
where T
is the desired type.
Of course someone must have write a function to convert something from the original type to T
…
There are several floating point types in Julia.
-
single
in MATLAB is the equivalent ofFloat32
-
double
in MATLAB is the equivalent ofFloat64
Additionally, there are
-
Float16
sometimes calledhalf
-
BigFloat
arbitrary precision floating point
julia> subtypes(AbstractFloat)
4-element Vector{Any}:
BigFloat
Float16
Float32
Float64
julia> p = 22/7
3.142857142857143
julia> typeof(p)
Float64
julia> p32 = Float32(p)
3.142857f0
julia> typeof(p32)
Float32
julia> p16 = Float16(p)
Float16(3.143)
julia> typeof(p16)
Float16
The convert(Float32, p)
example shown above is a more general way to do this for other types.
Note that if you have an array, you may want to use broadcasting to convert all elements of the array to the desired type.
julia> a = [1,2,3,4]
4-element Vector{Int64}:
1
2
3
4
julia> Float32.(a)
4-element Vector{Float32}:
1.0
2.0
3.0
4.0
There are some related types.
-
Rational
used to represent a number that is the quotient of two integers. -
Irrational
used to represent a number that cannot be expressed as a quotient of two integers
The method float
can be used to convert them to some kind of floating point value.
julia> r = 22//7
22//7
julia> typeof(r)
Rational{Int64}
julia> float(r)
3.142857142857143
julia> typeof(ans)
Float64
julia> pi
π = 3.1415926535897...
julia> typeof(pi)
Irrational{:π}
Floating point can yield some strange results:
julia> 0.1 + 0.2
0.30000000000000004
julia> big"0.1" + big"0.2"
0.3000000000000000000000000000000000000000000000000000000000000000000000000000017
julia> typeof(ans)
BigFloat
You can use rationals to help:
julia> 1//10 + 2//10
3//10
julia> float(ans)
0.3
There are some additional packages that can help:
julia> using FixedPointDecimals
julia> FixedDecimal{Int, 1}(0.1) + FixedDecimal{Int, 1}(0.2)
FixedDecimal{Int64,1}(0.3)
julia> float(ans)
0.3