Advertisement
cookchar

RationalApproxMk_VI_WRITER_PLUS

May 19th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.62 KB | None | 0 0
  1. #Coded by Charlie Cook on 4/19/16, Finalized on 4/23/16
  2. #Reminder: Pi to 18 Decimal Places is 3.141592653589793238
  3. #Reminder: e to 18 Decimal Places is 2.718281828459045235
  4.  
  5. from datetime import datetime
  6.  
  7. count = 0
  8. c = 0
  9. digits = 0
  10.  
  11. while (digits < 1 or c == int(c)):
  12.     c = float(input("Enter an Irrational Constant in decimal: "))
  13.     digits = len(str(c)) - len(str(int(c))) - 1
  14.     if (digits < 1 or c == int(c)):
  15.         print("\nError: The number needs to at least have one decimal point digit that is non-zero.\n")
  16.        
  17. n = int(c)
  18. d = 1
  19. p = 0
  20. dorp = " "
  21. showInTerminal = " "
  22. writeToFile = " "
  23.  
  24. while (dorp not in "DP" or dorp == "DP"):
  25.     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()
  26.     if (dorp not in "DP"):
  27.         print("\nError: Invalid Character.")
  28.     elif (dorp == "DP"):
  29.         print("\nError: You can't choose both.")
  30.        
  31. print("\nWARNING: AFFIRMING THE FOLLOWING TWO CONDITIONS IS NOT ADVISED IF")
  32. if (dorp == "D"):
  33.     print("YOUR PLANNED DIGIT LIMIT IS GREATER THAN 6.")
  34. elif (dorp == "P"):
  35.     print("YOUR PLANNED DECIMAL PRECISION IS GREATER THAN 3.")
  36.  
  37. while (showInTerminal not in "YN" or showInTerminal == "YN"):
  38.     showInTerminal = input("\nShould the program show individual results in the terminal/console? [Y/N]: ").upper()
  39.     if (showInTerminal not in "YN"):
  40.         print("\nError: Invalid Character.")
  41.     elif (showInTerminal == "YN"):
  42.         print("\nError: You can't choose both.")
  43.  
  44. while (writeToFile not in "YN" or writeToFile == "YN"):
  45.     writeToFile = input("\nShould the program write all results to a file? [Y/N]: ").upper()
  46.     if (writeToFile not in "YN"):
  47.         print("\nError: Invalid Character.")
  48.     elif (writeToFile == "YN"):
  49.         print("\nError: You can't choose both.")
  50.  
  51. resultsFile = open("rationalApproxResults.txt", "a")
  52.  
  53. if (dorp == "D"):      
  54.     g = len(str(n)+str(d))
  55.  
  56.     print("\nWARNING: PLEASE KEEP THE CUMULATIVE DIGIT LIMIT BELOW 15,\nPROGRAM SEIZURE OCCURS AT AND ABOVE THIS LIMIT.")
  57.     while (p < 2 or p < g):
  58.         p = int(input("\nEnter the number of desired cumulative digits in the resulting fraction: "))
  59.         if (p < 2 or p < g):
  60.             print("\nError: You need to have at least two cumulative digits,\nor however many non-decimal digits plus one that are in your constant.")
  61.    
  62.     startTime = str(datetime.now())
  63.     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
  64.     resultsFile.write(init)
  65.     print(init)
  66.  
  67.     bestResults = []
  68.     resultsFinal = []
  69.     resultsCurrent = []
  70.     if (g < p):
  71.         resultsCurrent.append([n / d, n, d, -1 * (c - n / d), "initial"])
  72.     elif (g == p):
  73.         resultsFinal.append([n / d, n, d, -1 * (c - n / d), "initial"])
  74.  
  75.     while (g <= p):
  76.         #button = input("Press enter for the next iteration.")
  77.         if (count == 0):
  78.             if (abs(c - ((n + 1) / d)) > abs(c - ((n - 1) / d))):
  79.                 lastop = "nm"
  80.                 n -= 1
  81.             else:
  82.                 lastop = "np"
  83.                 n += 1
  84.         else:
  85.             if (abs(c - ((n + 1) / d)) > abs(c - (n / (d + 1)))):
  86.                 lastop = "dp"
  87.                 d += 1
  88.             else:
  89.                 lastop = "np"
  90.                 n += 1
  91.                
  92.         f = n/d
  93.         diff = -1 * (c - f)
  94.         gTemp = len(str(n) + str(d))
  95.        
  96.         if (g < p and g == gTemp):
  97.             resultsCurrent.append([f, n, d, diff, lastop])
  98.         elif (g < p and g < gTemp):
  99.             diffs = []
  100.             for result in resultsCurrent:
  101.                 diffs.append(abs(result[3]))
  102.             bestOfCurrent = resultsCurrent[diffs.index(min(diffs))]
  103.             bestResults.append(bestOfCurrent)
  104.             resultsCurrent = []
  105.             if (gTemp < p):
  106.                 resultsCurrent.append([f, n, d, diff, lastop])
  107.             elif (gTemp == p):
  108.                 resultsFinal.append([f, n, d, diff, lastop])
  109.         elif (g == p and gTemp == p):
  110.             resultsFinal.append([f, n, d, diff, lastop])
  111.  
  112.         g = gTemp
  113.         count += 1
  114.        
  115.         if (writeToFile == "Y" or showInTerminal == "Y"):
  116.             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
  117.         if (writeToFile == "Y"):
  118.             resultsFile.write(res)
  119.         if (showInTerminal == "Y"):
  120.             print(res)
  121.    
  122.     diffs = []
  123.     for result in resultsFinal:
  124.         diffs.append(abs(result[3]))
  125.     bestOfFinal = resultsFinal[diffs.index(min(diffs))]
  126.     bestResults.append(bestOfFinal)
  127.    
  128.     diffs = []
  129.     for result in bestResults:
  130.         diffs.append(abs(result[3]))
  131.     bestOfAll = bestResults[diffs.index(min(diffs))]
  132.    
  133.     endTime = str(datetime.now())
  134.     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"
  135.     resultsFile.write(fin)
  136.     print(fin)
  137.     resultsFile.close()
  138.    
  139. elif (dorp == "P"):
  140.     digits = len(str(c)) - len(str(n)) - 1
  141.     print("\nDecimal Places in the Constant: " + str(digits))
  142.     while (p < 1 or p > digits):
  143.         p = int(input("\nEnter the number of decimal places to check the constant to: "))
  144.         if (p < 1 or p > digits):
  145.             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.")
  146.    
  147.     startTime = str(datetime.now())
  148.     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
  149.     resultsFile.write(init)
  150.     print(init)
  151.  
  152.     while (round(c, p) != round(n / d, p)):
  153.         #button = input("Press enter for the next iteration.")
  154.         if (count == 0):
  155.             if (abs(c - ((n + 1) / d)) > abs(c - ((n - 1) / d))):
  156.                 lastop = "nm"
  157.                 n -= 1
  158.             else:
  159.                 lastop = "np"
  160.                 n += 1
  161.         else:
  162.             if (abs(c - ((n + 1) / d)) > abs(c - (n / (d + 1)))):
  163.                 lastop = "dp"
  164.                 d += 1
  165.             else:
  166.                 lastop = "np"
  167.                 n += 1
  168.  
  169.         f = n/d
  170.         diff = -1 * (c - f)
  171.         count += 1
  172.        
  173.         if (writeToFile == "Y" or showInTerminal == "Y"):
  174.             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
  175.         if (writeToFile == "Y"):
  176.             resultsFile.write(res)
  177.         if (showInTerminal == "Y"):
  178.             print(res)
  179.    
  180.     endTime = str(datetime.now())
  181.     placeString = " Place"
  182.     if (p > 1):
  183.         placeString += "s"
  184.     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"
  185.     resultsFile.write(fin)
  186.     print(fin)
  187.     resultsFile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement