I wrote a tiny Swift programme to add a number to the previous number until it reached infinity. However, infinity is reached BEFORE the Double Maximum is reached.
Why is this? (I answered this below.)
Run it for yourselves:
import Foundation
import Darwin
var current: Double = 1
var previous: Double = 0
var register: Double = 0
var infinity = Double.infinity
var isInfinite = infinity.isInfinite
var n = 1
while current < infinity {
register = current
current = previous + register
print("\(n): \(current)")
guard current != infinity else { break }
previous = register
n += 1
}
print("\n")
print("Double limit is \(DBL_MAX)")
print("Distance to limit is \(DBL_MAX - register)")
print("Yet, \(previous) + \(register) reached infinity")
After adding:
print((DBL_MAX - register) - previous)
to the end of my code, I realised my error is not fully grasping e+
notation.
Thus, the above prints out:
-3.17059852116705e+307
showing that Double Max is over-shot in the final calculation, proving as to why infinity is reached.
Well, I've done my learning in public now!