Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand how define Types in Julia

Tags:

types

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.

like image 824
niandra82 Avatar asked Nov 28 '22 05:11

niandra82


2 Answers

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.

like image 117
Cameron Bieganek Avatar answered Dec 19 '22 21:12

Cameron Bieganek


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

like image 43
Dave Newton Avatar answered Dec 19 '22 22:12

Dave Newton