How to calculate phi with a random number generator?

324 Views Asked by At

I recently saw this as an interview question and was completely stumped by it..

Calculate phi using numpy.random.uniform

I was thinking $$a + \frac{b}{a} = \frac{a}{b} $$

might be useful in that you could simply generate random numbers between 0 and 1 and assign to $A$. You can then generate a new number from 0 to 1 and keep it if it satisfied the equality. In the end you can just divide the means of the generated quanitities.

1

There are 1 best solutions below

0
On BEST ANSWER

What you need to focus on is $$1 + \frac{1}{\phi} = \phi$$

You can select upper and lower boundaries for your random number and see how it behaves in this equation, then update the boundaries to get a new random number. Loop this many times and you will be converging to the golden ratio.

import numpy as np

def get_phi(low, up, loop):
    for i in range(loop):
        phi = np.random.uniform(low, up)
        if phi < 1 + 1/phi:
            low = phi
        else:
            up = phi

    return phi

print(get_phi(0, 2, 100))

This gave me $1.6180339887498947$ which is close enough.