2.9 Arithmetic in Julia
Julia is capable of dealing with several types of numbers, from integers to complex numbers, as well as fractions. Some of those numbers, like \(\sqrt 2\) or \(pi\), do not have a rigorous representation based in numerals and, for that reason, Julia classifies them as inexact numbers to emphasize the fact that we are dealing with an approximate value. When an inexact number is used in an arithmetic operation, the result will also be inexact, so the inexactness is said to be contagious.
Finitude is another feature of some types of numbers, meaning that those numbers cannot surpass a certain limit, above which every number is represented by infinity, as you can see by the following example that uses inexact numbers:
> 10.0^10
1.0e10
> 10.0^100
1.0e100
> 10.0^1000
Inf
Note that Inf (or -Inf) is Julia’s way of saying that a number exceeds the representation capacity. The number is not infinite, as one might think, but merely a value excessively big.
There is also another problem regarding inexact numbers: round-off errors. As an example, consider the obvious equality \((4/3-1)*3-1=0\) and note its result in Julia:
> (4/3-1)*3-1
-2.220446049250313e-16
As is possible to see, we did not obtain the correct result due to representation and round-off errors: 4/3 cannot be represented with a finite number of digits. This round-off error is then propagated to the remaining operations, producing a value that is not zero but is close to zero.
2.9.1 Exercises 6
2.9.1.1 Question 18
Translate the following definition to Julia: \[f(x)=x-0.1\cdot{}(10\cdot{}x-10)\]
2.9.1.2 Question 19
In mathematical terms, whatever the argument used in the previously mentioned function is, the result should always be \(1\), since \[f(x)=x-0.1\cdot{}(10\cdot{}x-10)=x-(x-1)=1\] Using the function defined in the previous exercise, evaluate the following expressions and explain the results:
f(5.1)
f(51367.7)
f(176498634.7)
f(1209983553611.9)
f(19843566622234755.9)
f(553774558711019983333.9)
2.9.1.3 Question 20
We wish to create a flight of stairs with \(n\) treads, covering a height \(a\) in meters. Considering that each step has a rise height \(h\) and a tread depth \(d\) that obey to the following proportion: \[2h+d=0.64\]
Define a function that, from a given height to cover and the number of treads, computes the length of the flight of stairs.