liveBook · Manning

Floating-point arithmetic

As explained in Julia as a Second Language

A floating-point number is a finite-precision numerical representation that stores a sign, significant digits, and an exponent to approximate real values.

A calculator gives you a quick numerical answer; Julia also lets you inspect what kind of number produced it. Floating-point numbers come in different bit lengths. The default, Float64, uses 64 bits (8 bytes). More bits can support larger values and higher precision, though a graphics calculation may need less precision than a scientific one. section 2.0 section 2.4

julia> 42.98      #1
42.98
 
julia> typeof(ans)
Float64
 
julia> 34.23f0    #2
34.23f0
 
julia> typeof(ans)
Float32

Compare the types of `42.98` and `34.23f0`: an ordinary decimal literal is Float64, while the `f0` suffix makes a Float32 literal. section 2.4

The zero in `f0` matters. Unlike an `f` suffix in Java or C/C++, `0.5f` in Julia is interpreted as multiplication by a variable named `f`. For a 16-bit value, convert explicitly with `Float16(3.5)`. Types can also change across an operation: `Float16(4) + 5f0` produces a Float32 result. section 2.4

Choose the result you need

In the REPL, `4/2` returns `2.0` and `5/2` returns `2.5`: `/` produces a floating-point result even for integer inputs. If you need the integer quotient and remainder instead, use `div(5, 2)` for `2` and `rem(5, 2)` for `1`. section 2.4.1

Rounding is a separate choice. `floor(3.6)` returns `3.0`, `ceil(3.2)` returns `4.0`, and `round(3.5)` returns `4.0`. These results are still floating-point values; use `round(Int64, 3.5)` when you want an integer result. section 2.5.4

How Julia as a Second Language covers it

How deep it goes
Works through Julia literals, bit lengths, conversions, division, and rounding, but defers unfamiliar number-type concepts to an appendix.
Examples
Shows REPL checks with `typeof`, Float32’s `f0` suffix, mixed-type addition, division, and rounding functions.
What it assumes
Starts with calculator-style arithmetic and introduces Julia number types; directs readers elsewhere for unfamiliar number-type concepts.
What you can do after
Practice/perform Julia calculations while choosing floating-point types and selecting division or rounding operations for the desired result.
How it connects
Connects floating-point arithmetic to integer types, bit length, type conversion, division, and rounding.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.