Is the golden ratio defined in Python?
There isn't. However, since you are importing math anyway, phi may be calculated the same way pi would be calculated:
>>> import math
>>> pi = 4 * math.atan(1)
>>> pi
3.141592653589793
>>> pi = math.acos(-1)
>>> pi
3.141592653589793
>>> math.pi
3.141592653589793
>>> phi = ( 1 + math.sqrt(5) ) / 2
>>> phi
1.618033988749895
The reason math has pi and e defined but not phi may be because no one asked for it.
The python math docs says math.pi is "The mathematical constant π = 3.141592..., to available precision". However, you may calculate four times the arc tangent of one and get roughly the same result: pi = 4 * math.atan(1)
, or pi = math.acos(-1)
:
>>> math.pi == math.acos(-1) == 4 * math.atan(1)
True
The same could be said about phi, which is not readily available as math.phi
but you may find the nearest available precision with the solution to the quadratic equation x² + x -1 = 0: phi = ( 1 + math.sqrt(5) ) / 2
.
scipy.constants
defines the golden ratio as scipy.constants.golden
. It is nowhere defined in the standard library, presumably because it is easy to define yourself:
golden = (1 + 5 ** 0.5) / 2