Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Coded by Charlie Cook on 4/19/16, Finalized on 4/23/16
- #Reminder: Pi to 18 Decimal Places is 3.141592653589793238
- #Reminder: e to 18 Decimal Places is 2.718281828459045235
- from datetime import datetime
- count = 0
- c = 0
- digits = 0
- while (digits < 1 or c == int(c)):
- c = float(input("Enter an Irrational Constant in decimal: "))
- digits = len(str(c)) - len(str(int(c))) - 1
- if (digits < 1 or c == int(c)):
- print("\nError: The number needs to at least have one decimal point digit that is non-zero.\n")
- n = int(c)
- d = 1
- p = 0
- dorp = " "
- showInTerminal = " "
- writeToFile = " "
- while (dorp not in "DP" or dorp == "DP"):
- dorp = input("\nEnter 'D' to calculate a fraction to some number of total fraction digits,\nor 'P' to calculate a fraction accurate to some number of deicmal places: ").upper()
- if (dorp not in "DP"):
- print("\nError: Invalid Character.")
- elif (dorp == "DP"):
- print("\nError: You can't choose both.")
- print("\nWARNING: AFFIRMING THE FOLLOWING TWO CONDITIONS IS NOT ADVISED IF")
- if (dorp == "D"):
- print("YOUR PLANNED DIGIT LIMIT IS GREATER THAN 6.")
- elif (dorp == "P"):
- print("YOUR PLANNED DECIMAL PRECISION IS GREATER THAN 3.")
- while (showInTerminal not in "YN" or showInTerminal == "YN"):
- showInTerminal = input("\nShould the program show individual results in the terminal/console? [Y/N]: ").upper()
- if (showInTerminal not in "YN"):
- print("\nError: Invalid Character.")
- elif (showInTerminal == "YN"):
- print("\nError: You can't choose both.")
- while (writeToFile not in "YN" or writeToFile == "YN"):
- writeToFile = input("\nShould the program write all results to a file? [Y/N]: ").upper()
- if (writeToFile not in "YN"):
- print("\nError: Invalid Character.")
- elif (writeToFile == "YN"):
- print("\nError: You can't choose both.")
- resultsFile = open("rationalApproxResults.txt", "a")
- if (dorp == "D"):
- g = len(str(n)+str(d))
- print("\nWARNING: PLEASE KEEP THE CUMULATIVE DIGIT LIMIT BELOW 15,\nPROGRAM SEIZURE OCCURS AT AND ABOVE THIS LIMIT.")
- while (p < 2 or p < g):
- p = int(input("\nEnter the number of desired cumulative digits in the resulting fraction: "))
- if (p < 2 or p < g):
- print("\nError: You need to have at least two cumulative digits,\nor however many non-decimal digits plus one that are in your constant.")
- startTime = str(datetime.now())
- init = "\n---{ Beginning of Digit Run on " + startTime + " }---\n\nInitial Parameters:\n\nNumerator 'n': " + str(n).rjust(21) + "\nDenominator 'd' : " + str(d).rjust(18) + "\nConstant 'c': " + str(c).rjust(22) + "\nDigit Limit 'p': " + str(p).rjust(19) + "\n" + "-" * 36
- resultsFile.write(init)
- print(init)
- bestResults = []
- resultsFinal = []
- resultsCurrent = []
- if (g < p):
- resultsCurrent.append([n / d, n, d, -1 * (c - n / d), "initial"])
- elif (g == p):
- resultsFinal.append([n / d, n, d, -1 * (c - n / d), "initial"])
- while (g <= p):
- #button = input("Press enter for the next iteration.")
- if (count == 0):
- if (abs(c - ((n + 1) / d)) > abs(c - ((n - 1) / d))):
- lastop = "nm"
- n -= 1
- else:
- lastop = "np"
- n += 1
- else:
- if (abs(c - ((n + 1) / d)) > abs(c - (n / (d + 1)))):
- lastop = "dp"
- d += 1
- else:
- lastop = "np"
- n += 1
- f = n/d
- diff = -1 * (c - f)
- gTemp = len(str(n) + str(d))
- if (g < p and g == gTemp):
- resultsCurrent.append([f, n, d, diff, lastop])
- elif (g < p and g < gTemp):
- diffs = []
- for result in resultsCurrent:
- diffs.append(abs(result[3]))
- bestOfCurrent = resultsCurrent[diffs.index(min(diffs))]
- bestResults.append(bestOfCurrent)
- resultsCurrent = []
- if (gTemp < p):
- resultsCurrent.append([f, n, d, diff, lastop])
- elif (gTemp == p):
- resultsFinal.append([f, n, d, diff, lastop])
- elif (g == p and gTemp == p):
- resultsFinal.append([f, n, d, diff, lastop])
- g = gTemp
- count += 1
- if (writeToFile == "Y" or showInTerminal == "Y"):
- res = "\nNumerator 'n': " + str(n).rjust(21) + "\nDenominator 'd': " + str(d).rjust(19) + "\nFraction 'f' (n / d): " + str(round(f, 8)).rjust(14) + "\nNet Difference: " + str(round(diff, 8)).rjust(20) + "\nLast Operation: " + lastop.rjust(20) + "\nIteration Count: " + str(count).rjust(19) + "\n" + "-" * 36
- if (writeToFile == "Y"):
- resultsFile.write(res)
- if (showInTerminal == "Y"):
- print(res)
- diffs = []
- for result in resultsFinal:
- diffs.append(abs(result[3]))
- bestOfFinal = resultsFinal[diffs.index(min(diffs))]
- bestResults.append(bestOfFinal)
- diffs = []
- for result in bestResults:
- diffs.append(abs(result[3]))
- bestOfAll = bestResults[diffs.index(min(diffs))]
- endTime = str(datetime.now())
- fin = "\nFinal Results:\n\nDigit Limit 'p': " + str(p).rjust(19) + "\nConstant 'c': " + str(c).rjust(22) + "\nBest Fraction 'f': " + (str(bestOfAll[1]) + " / " + str(bestOfAll[2]) + ",").rjust(17) + "\n" + ("(or " + str(bestOfAll[0]) + ")").rjust(36) + "\nNet Difference: " + str(round(bestOfAll[3], 8)).rjust(20) + "\nPercent Error: " + (str(round(100 * abs((bestOfAll[0] - c) / c), 8)) + " %").rjust(21) + "\nFinal Iteration Count: " + str(count).rjust(13) + "\n\n---{ Conclusion of Digit Run on " + endTime + " }---\n"
- resultsFile.write(fin)
- print(fin)
- resultsFile.close()
- elif (dorp == "P"):
- digits = len(str(c)) - len(str(n)) - 1
- print("\nDecimal Places in the Constant: " + str(digits))
- while (p < 1 or p > digits):
- p = int(input("\nEnter the number of decimal places to check the constant to: "))
- if (p < 1 or p > digits):
- print("\nError: You need to check to at least one decimal place.\nAlso, you can't check to more decimal places than those of the constant you entered.")
- startTime = str(datetime.now())
- init = "\n---{ Beginning of Precision Run on " + startTime + " }---\n\nInitial Parameters:\n\nNumerator 'n': " + str(n).rjust(21) + "\nDenominator 'd' : " + str(d).rjust(18) + "\nConstant 'c': " + str(c).rjust(22) + "\nDecimal Precision 'p': " + str(p).rjust(13) + "\n" + "-" * 36
- resultsFile.write(init)
- print(init)
- while (round(c, p) != round(n / d, p)):
- #button = input("Press enter for the next iteration.")
- if (count == 0):
- if (abs(c - ((n + 1) / d)) > abs(c - ((n - 1) / d))):
- lastop = "nm"
- n -= 1
- else:
- lastop = "np"
- n += 1
- else:
- if (abs(c - ((n + 1) / d)) > abs(c - (n / (d + 1)))):
- lastop = "dp"
- d += 1
- else:
- lastop = "np"
- n += 1
- f = n/d
- diff = -1 * (c - f)
- count += 1
- if (writeToFile == "Y" or showInTerminal == "Y"):
- res = "\nNumerator 'n': " + str(n).rjust(21) + "\nDenominator 'd': " + str(d).rjust(19) + "\nFraction 'f' (n / d): " + str(round(f, 8)).rjust(14) + "\nNet Difference: " + str(round(diff, 8)).rjust(20) + "\nLast Operation: " + lastop.rjust(20) + "\nIteration Count: " + str(count).rjust(19) + "\n" + "-" * 36
- if (writeToFile == "Y"):
- resultsFile.write(res)
- if (showInTerminal == "Y"):
- print(res)
- endTime = str(datetime.now())
- placeString = " Place"
- if (p > 1):
- placeString += "s"
- fin = "\nFinal Results:\n\nDecimal Precision 'p': " + (str(p) + placeString).rjust(13) + "\nConstant 'c': " + (str(c) + ",").rjust(22) + "\n" + ("(rounds to " + str(round(c, p)) + ")").rjust(36) + "\nBest Fraction 'f': " + (str(n) + " / " + str(d) + ",").rjust(17) + "\n" + ("(is " + str(f) + ",").rjust(36) + "\n" + ("rounds to " + str(round(f, p)) + ")").rjust(36) + "\nNet Difference: " + str(round(diff, 8)).rjust(20) + "\nPercent Error: " + (str(round(100 * abs((f - c) / c), 8)) + " %").rjust(21) + "\nFinal Iteration Count: " + str(count).rjust(13) + "\n\n---{ Conclusion of Precision Run on " + endTime + " }---\n"
- resultsFile.write(fin)
- print(fin)
- resultsFile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement