In this lesson we take a look at Floating-Point values and the
f64 types. We'll also look at the different ways of defining and creating values of such types.
Instructor: [00:00] In Rust there are two different floating-point types. These are f32 and f64, which have a number range from very negative to very positive, including positive infinity and negative infinity.
[00:16] Floating point type values can be defined in many different ways, and here are some of them. For example, here we have -1.2345 or 3.nothing. There's also 034. What's important is that a floating point has different parts to it. There's the fractional part. There can also be an exponential part. This number right here says it's 1^4.
[00:45] Generally, what Rust will do is infer the type based on the value that is assigned. If both types would fit, so that is either f32 or f64, Rust will use f64 by default. It's also possible to apply a type suffix as part of the number, as we can see here. f5 is actually 32 of type f32. In this case, Rust will not infer the type because it's explicitly annotated.
[01:14] Here is another example of a floating-point type that includes all the parts that such a value can have. We have an integer part, then a fractional part, then exponential with a negative value, and a type annotation. All of these different parts of a fractional number are optional, but there has to be at least one of them to make the value a floating-point type.
[01:40] It's also important to note that Rust will never implicitly interpret an integer type as a floating-point type or vice versa. That's why in this particular case here, 32 would be an integer type. However, since there is the explicit annotation, Rust will interpret it as a floating-point type.
If both types would fit, so that is either f32 or f64, Rust will use f64 by default.
Why default to
f64 (which I assume takes more memory)? I would have expected the opposite.
once again a very good question that I also find very hard to answer. As you know, I'm certainly not in the position to explain certain design decisions of the language, however I've done some research and ran into this Reddit post: https://www.reddit.com/r/rust/comments/50480b/floating_point_numbers_in_rust/
The author of the post asks pretty much the same question and people seem to mostly answer that Rust followed what
C/C++ is doing (more or less,
double which is the default type for numbers as per comments, and takes 64 bits as well).
One comment says that it's not just necessarily because
C did it this way but more because of the same reasons why
C did it this way. Unfortunately, they don't seem too elaborate on the "why" here...
Wish I could provide a better answer.