niandra82
niandra82

Reputation: 255

I don't understand how define Types in Julia

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.

Upvotes: 4

Views: 168

Answers (4)

Nils Gudat
Nils Gudat

Reputation: 13800

The problem is that the input 64.0 is automatically a Float64:

julia> typeof(64.0)
Float64

Therefore you want to directly construct a Float32 like so:

julia> Float32(64.0)
64.0f0

julia> typeof(ans)
Float32

Upvotes: 5

Cameron Bieganek
Cameron Bieganek

Reputation: 7704

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.

Upvotes: 9

Chris Rackauckas
Chris Rackauckas

Reputation: 19162

The syntax you wrote down is, you defined a Float64 and then declared that it should be a Float32, and so it rightly throws an error saying that's not compatible. 64.0 or 64e0 is a Float64, while 64f0 is a Float32. So x = 64f0 is all you need. Such type assertions are generally not needed except for controlling dispatch or defining the fields of a struct.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160321

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 :)

Upvotes: 8

Related Questions