How do you subtract Double.pi and Float.pi in Swift?

Viewed 208

I want to do Double.pi - Float.pi, but I am getting an error:

Binary operator '-' cannot be applied to operands of type 'Double' and 'Float.

When I typecast Float to Double or Double to Float (for example: Double(Float.pi)), the result is wrong. How can I subtract them?

let floatPi = Float.pi
let Pi = Double.pi
print("float pi = \(floatPi)")
print("double pi = \(Pi)")
let substraction = Pi - floatPi
print(substraction)

Here is the result from the above:

float pi = 3.1415925

double pi = 3.141592653589793

error: MyPlayground.playground:20:23: error: binary operator '-' cannot be applied to operands of type 'Double' and 'Float' let substraction = Pi - floatPi

When I try this:

let floatPi = Double(Float.pi)

The result is:

float pi = 3.141592502593994

double pi = 3.141592653589793

1.5099579897537296e-07

1 Answers

The reason you are seeing a difference is that Double can represent the value of π more accurately, because it uses more bits to get more precision. Both Float.pi and Double.pi are created by representing the mathematical value of π as accurately as possible in the Float or Double type without exceeding the mathematical value (the value of π is rounded to the nearest representable value in the direction of zero). So Float.pi and Double.pi have different values, and subtracting them produces about 1.5•10−7.

Further, the decimal numerals you see when you print Float.pi or Double.pi with default formatting are not the actual values inside the computer. Both Float and Double use a binary format in which each number is represented as a significand (in effect, some integer) multiplied by a negative power of two (including negative powers of 2, such as 2−34, for example). So the actual value of Float.pi is 3.141592502593994140625, and the actual value of Double.pi is 3.141592653589793115997963468544185161590576171875.

Related