Numpy Project Euler Problem 2: 1. Calculate The Golden Ratio
Numpy Project Euler Problem 2: 1. Calculate The Golden Ratio
net
We get the result 33.2629480359. You can double check this yourself from the Wikipedia article.
The output is below. You can plug this right into an unit test, if you want.
1 First 9 Fibonacci Numbers [ 1. 1. 2. 3. 5. 8. 13. 21. 34.]
5. Convert to integers
This step is optional. I think its nice to have an integer result at the end. Its like the difference between Mawashi Geri and Mawashi Geri Koshi. The effect is almost the same, but one feels better than the other. OK, I actually wanted to show you the astype function.
1 fib = fib.astype(int) 2 print "Integers", fib
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. #By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four mil #find the sum of the even-valued terms. #1. Calculate phi phi = (1 + numpy.sqrt(5))/2 print "Phi", phi #2. Find the index below 4 million n = numpy.log(4 * 10 ** 6 * numpy.sqrt(5) + 0.5)/numpy.log(phi) print n #3. Create an array of 1-n n = numpy.arange(1, n) print n #4. Compute Fibonacci numbers fib = (phi**n - (-1/phi)**n)/numpy.sqrt(5) print "First 9 Fibonacci Numbers", fib[:9]
26 27 28 29 30 31 32 33 34 35 36 37
#5. Convert to integers # optional fib = fib.astype(int) print "Integers", fib #6. Select even-valued terms eventerms = fib[fib % 2 == 0] print eventerms #7. Sum the selected terms print eventerms.sum()
That was quite a workout. More katas to come soon. Please stay tuned. If you liked this post and are interested in NumPy check out NumPy Beginners Guide by yours truly.