Advertisement
Guest User

Floor of multiples of the golden ratio

a guest
Mar 20th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. def fNphi(n):
  2.   '''Calculates ⌊nϕ⌋ based on https://math.stackexchange.com/revisions/3155517/1. The general idea is that since ϕ^2 - ϕ - 1 = 0, we have that (nϕ)^2 - n(nϕ) - n^2 = (n^2)ϕ^2 - (n^2)ϕ - n^2 = 0. We use bisection to find the two integers nearest the root, which will be nϕ. The smaller one will be ⌊nϕ⌋.'''
  3.   assert isinstance(n, int) #In Python 3.0, `int` repersents arbitrary precision integers. This algorithm uses arbitrary precision integer arithmetic.
  4.   n2 = n**2 #Might as well cache it.
  5.   pos = 2*n #The polynomial is always positive for this input.
  6.   neg = n #The polynomial is always negative for this input.
  7.   while abs(pos - neg) > 1:
  8.     mid = (pos + neg) // 2
  9.     if mid * (mid - n) - n2 > 0: #Horner's method of calculating polynomials
  10.       pos = mid
  11.     else: neg = mid
  12.   return min(neg, pos) #If n is negative, neg will be greater than pos. To cover all cases, we use min.
  13.  
  14. for i in tuple(range(-10, 10+1)) + (-237506420978245709325430, 1274070832474234842304895): #Some arbitrary values to test the function on
  15.   print(f'{i:3}: {fNphi(i):3}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement