Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def fNphi(n):
- '''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ϕ⌋.'''
- assert isinstance(n, int) #In Python 3.0, `int` repersents arbitrary precision integers. This algorithm uses arbitrary precision integer arithmetic.
- n2 = n**2 #Might as well cache it.
- pos = 2*n #The polynomial is always positive for this input.
- neg = n #The polynomial is always negative for this input.
- while abs(pos - neg) > 1:
- mid = (pos + neg) // 2
- if mid * (mid - n) - n2 > 0: #Horner's method of calculating polynomials
- pos = mid
- else: neg = mid
- return min(neg, pos) #If n is negative, neg will be greater than pos. To cover all cases, we use min.
- for i in tuple(range(-10, 10+1)) + (-237506420978245709325430, 1274070832474234842304895): #Some arbitrary values to test the function on
- print(f'{i:3}: {fNphi(i):3}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement