I'm learning Julia, and I'm just a little bit confused about Types. Mine is a very basic question. I understand that if I write
x = 64.0::MyType
x should be contain the value 64, with Type equal to MyType. But if I write
x = 64.0::Float32
I get the error
ERROR: TypeError: in typeassert, expected Float32, got Float64
I found that the following does not give me an error
x = convert(Float32,64.0)
Is this the right approach? It seems too convoluted.
The answers from @NilsGudat and @DaveNewton are both correct but incomplete, so let me provide some elaboration.
It's important to note that your first example, x = 64.0::MyType
, is not how you create a number of type MyType
. The notation a::MyType
, when it occurs on the right-hand side of an expression, is a type assertion. It will return the value of a
if a
is a subtype of MyType
(a isa MyType
), but if a
is not a subtype of MyType
it throws an exception. In your everyday Julia code, you are not likely to need this very often. For more information on type declarations and assertions, see the manual section on type declarations and this section from the performance tips.
As @DaveNewton points out, Julia provides a literal syntax for creating Float32
numbers. The syntax is analogous to the scientific notation for Float64
, e.g. 4.5e2
, except the e
is replaced with an f
:
julia> 4.5f2
450.0f0
julia> 450f0
450.0f0
julia> typeof(4.5f2)
Float32
Note that attaching ::Float32
to a Float32
literal value is not necessary and is in fact redundant. So instead of writing x = 64.0f0::Float32
as suggested by @DaveNewton, you can just write x = 64.0f0
.
Julia defaults to Float64
. Float32
literals need an f
(as opposed to an e
):
x = 64.0f0::Float32
As Renat adds:
https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/
(Which is what I used to answer this question since I don't know Julia. But I know how to search :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With