Is the golden ratio defined in Python?

Question:

Is there a way to get the golden ratio, phi, in the standard python module? I know of e and pi in the math module, but I might have missed phi defined somewhere.

Asked By: dwitvliet

||

Answers:

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
Answered By: Lynn

The standard library doesn’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 regular formula: phi = ( 1 + math.sqrt(5) ) / 2.


Libraries that define or provide a "shortcut" to the golden ratio are these:

Scipy

Scipy calculates a static value for the algebraic formula using standard math package at import time and it’s the same thing as defining it yourself (specifically to cpython both will be computed at compile time):

import math as _math
golden = golden_ratio = (1 + _math.sqrt(5)) / 2
print(golden)

MpMath

Mpmath calculates the algebraic formula at call time to supplied precision:

import mpmath
print(mpmath.mp.phi)

Sympy

The closest thing to a definition of golden ratio is the sympy’s singleton GoldenRatio which uses the mpmath float (mpf) calculated at call time:

import sympy
print(float(sympy.S.GoldenRatio))

Sage

Sage Math goes further allowing you to calculate phi in many different ways.

Answered By: Iuri Guilherme
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.