Created
October 4, 2014 12:12
-
-
Save mhp/7a439fafaa07f7e5e9fd to your computer and use it in GitHub Desktop.
Square root sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" Ascending/descending sequence spotter, looking | |
for sequences in the first decimal places of | |
square roots. | |
https://twitter.com/standupmaths/status/518081757019906048 | |
""" | |
import decimal | |
import json | |
import signal | |
stateFile = 'sqrtSeq.json' | |
savePeriod = 3600 | |
# Restore saved state, so we can continue from where we left off | |
try: | |
state = json.load(file(stateFile, 'r')) | |
curLen = state['length'] | |
i = state['current'] | |
print "Restored state: ", i, curLen | |
except: | |
curLen = 5 | |
i=1 | |
print "Initial state: ", i, curLen | |
# Ensure we have enough precision to resume | |
decimal.getcontext().prec = curLen*2 | |
# Save state on ctrl-c or every hour, just to be safe | |
def saveState(sig, frame): | |
print "Saving state: ", i, curLen | |
state = { 'current': i, 'length': curLen} | |
json.dump(state, file(stateFile, 'w')) | |
if sig == signal.SIGINT: | |
exit(1) | |
signal.signal(signal.SIGINT, saveState) | |
if savePeriod > 0: | |
signal.signal(signal.SIGALRM, saveState) | |
signal.setitimer(signal.ITIMER_REAL, savePeriod, savePeriod) | |
def ascRun(a): | |
""" Measure the length of the ascending sequence in a """ | |
for i in range(len(a)-1): | |
if a[i] > a[i+1]: | |
return i+1 | |
return len(a) | |
def dscRun(a): | |
""" Measure the length of the descending sequence in a """ | |
for i in range(len(a)-1): | |
if a[i] < a[i+1]: | |
return i+1 | |
return len(a) | |
while True: | |
root = str(decimal.Decimal(i).sqrt()) | |
if '.' in root: | |
fract = root.split('.')[1] | |
if ascRun(fract) >= curLen: | |
print "ASC", i, ascRun(fract), root | |
curLen = ascRun(fract) | |
decimal.getcontext().prec = curLen*2 | |
elif dscRun(fract) >= curLen: | |
print "DSC", i, dscRun(fract), root | |
curLen = dscRun(fract) | |
decimal.getcontext().prec = curLen*2 | |
i += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment