Reputation:
import math
phi = math.sqrt(5) / 2
pi = (802 * phi - 801) / (602 * phi - 601)
pi = round(pi ^ 4)
print("Pi is equivalent to", pi)
I am trying to create a program that calculates the approximate value of pi., However, it returns an error in line 4.
What is wrong here? Both pi and 4 ar either integers or floats so shouldn't exponents be fine?
Traceback (most recent call last):
File "C:/Users/Chris/Desktop/run module.py", line 4, in <module>
pi = round(pi ^ 4)
TypeError: unsupported operand type(s) for ^: 'float' and 'int'
Upvotes: 1
Views: 10246
Reputation: 8814
That's not the exponentiation (i.e., power) operator in Python. You want **
instead of ^
.
import math
phi = math.sqrt(5) / 2
pi = (802 * phi - 801) / (602 * phi - 601)
pi = round(pi ** 4)
print("Pi is equivalent to", pi)
Granted, this won't give a great result. It'll just give you 3
because of the round
call.
If you want something slightly better, remove the rounding. Change that error line to:
pi = pi ** 4
Now you'll get 3.1066259768762885
. Not perfect, but certainly better.
Of course, another fun way to approximate pi comes from Randall Munroe.
But you want something exact to 7 decimal places, and your approximation should be.
Another approximation involving the golden ratio phi is given by pi approx ((802phi-801)/(602phi-601))^4,
(18) which is good to 7 digits (K. Rashid, pers. comm.).
The issue is that your definition of phi
is incorrect. Try phi = (1 + math.sqrt(5)) / 2
.
import math
phi = (1 + math.sqrt(5)) / 2 # Correct definition for golden ratio
pi = (802 * phi - 801) / (602 * phi - 601)
pi = round(pi ** 4, 7)
print("Pi is equivalent to", pi)
You'll get 3.1415926
, as was sought.
Upvotes: 4
Reputation: 53
import math
phi = math.sqrt(5) / 2
pi = (802 * phi - 801) / (602 * phi - 601)
pi = round(pi ** 4) #CHANGES MADE HERE
print("Pi is equivalent to", pi)
Should make it work because you had used '^' or the Bitwise Operator. For exponents, use '**'.
Upvotes: 2