192 61 8MB
English Pages [285]
Python for the TI-84 Powerful Python programs and games for the TI-84 Plus CE Python graphing calculator
by John Clark Craig
Table of Contents Acknowledgements Introduction Programs
1. Calendar Functions CALENDAR DATE DATEPLUS DAYSDATS JULIAN 2. Electronics AVGPKRMS BRIDGE DELTAWYE FREQWAVE LED_RES OHMSLAW PARALLEL RCTIMING SERIES ZROUND 3 Games and Chance DECKCRDS DICE DIGITS FACTCBPM HEADSROW HUNT_DIR
HUNT_DIS JUMBLE MAZE MEMORY MNTYHALL PI_BUFFN PI_DARTS RNDMBYTE WORDPERM 4. GPS and Navigation GPS_AREA GPS_DIST MIDPOINT NAVIGATE 5. Money and Finance DEPOSITS FUTURVAL INTEREST MONTHS PAYMENTS PRNCIPAL 6. Numerical Calculations BINHXDEC BINSRCH FACTORS FIBONACC GCD_LCM GLDRATIO NEWTON PRIMES QUADRATC REC_POLR
SIMULTEQ VECTORS 7. Other Useful Programs CONCRETE CRICKETS LASERDIS MPH SECRET WAIT_KEY WET_BULB WNDCHILL 8. Plane Geometry ARCS AREA_3P AREA_3S AREA_PTS CIRCLE3P DISTANCE DIVLINE LINE_2P LINSLOPE TRANSFRM TRIANG3P TRIANGLE 9. Space Geometry COORD_3D DIVLIN3D ROTATE3D TRIANG3D VOLUME4P 10. Space Sciences
GEOSYNC MOON PENNIES RADIOISO RELATVTY SPACEANG STN_GRAV SUN_ELEV SUBSOLAR About the Author Other Books By John Clark Craig
Introduction Why Python?
Python, the world's most popular programming language, is an ideal language for handheld calculators. The syntax is concise, easy to read, and easy to understand, even for beginners. The language is non-proprietary, so it runs everywhere, even on desktop and laptop computers with only minor modifications from what you'll find in this book, and even then only in a very few cases. Python handles number crunching well, and with its lists, strings, and other data structures, it powerfully handles a very wide variety of programming tasks. But perhaps the biggest advantage of learning Python via your programmable calculator is that this knowledge will be applicable and useful no matter what computers or systems you might work with in the future. Learn it once and you'll have a new life skill of great value. Python in your calculator
Most of the number crunching that takes place in Python programs is straightforward and easy to understand. When it comes to interacting with the user to request input and output (commonly referred to as I/O) there are some optional approaches, and understanding some of these make it easier for you to make shorter programs, or longer but more user friendly programs, depending on your style and programming goals. The programs in this book use several of these approaches, and it's important to know that you can change these programs if you prefer one type of programming over another. An excellent way to leverage Python in your calculator is to simply define functions in a "program" file. When you run the program, nothing visibly happens. But the function definitions are effectively added to your calculator's toolbox, ready for your use while working in the shell. For example, here's a very short program that defines a function named add(). def add(x,y): return x+y
After you run this program, in the shell you can type something like "add(3,4)" to get 7, or to add any two numbers or variables together. Or, rather than type the function names yourself, on your TI-84 CE Plus Python calculator, you can select "4:vars..." from the [Tools] menu to access a quick list of functions your program has defined. More complicated functions can add some powerful new capabilities to your computation toolbox! Many of the programs in this book were created as sets of function definitions in this way. This keeps the programs very short and easier to enter. In some cases, the programs also printed some instructions and reminders on how to use the functions, for easy reference. Take a look at the vectors program near the end of chapter 6 for a good example of how to add helpful instructions, while just defining functions for later use in the shell. The standard way to create standalone programs in most programming languages is to prompt the user for input data, and then to process that data in a meaningful way to create output for the user. Throughout this book there are several programs where you are asked to type data in response to a prompt at run time, and then the calculations begin. Take a look at the primes program, also in chapter 6, for an example where the program asks you to enter the starting point to look for primes, and the number of those primes to find. There are a few other useful I/O tricks presented in several of the programs in this book. It is sometimes useful to ask for a number, but to let the user simply press [enter] without entering a number if they don't know the value. This is actually a tricky thing to do, as a simple assignment to a variable after an input() function call can fail if nothing is input. Take a close look at the program ARCS, in chapter 8 for an example where any combination of two of four variables can be entered, and the missing ones will be calculated. Here's a pair of code lines where an angle is entered, or a value of zero is put in place if the user simply presses [enter]. a=input("Angle (deg): ") a=float(a) if a else 0
Finally, note that the Python shell itself provides a powerful calculation environment. Rather than edit and save a program, sometimes it's faster and more efficient to simply type calculations line-by-line interactively in the shell. Several of the keys on your TI-84 Plus CE Python calculator are redefined when in the Python environment, and learning how to leverage them can provide some really cool results. For example, the [2nd][ans] key enters an underscore in the Python shell, and it turns out the underscore is a special temporary variable that contains the results of the last calculation. Here's a quick example that results from first entering 3 and pressing the xsquared key, then using [2nd][ans] to triple the result.
Learn by Examples There are many, many resources online and in other books to learn the intricacies of the Python language. The goal of this book isn't to duplicate all this information. Instead, there's a lot of short, useful programs that you can use "right out of the box", and in putting them to use you'll learn a lot about Python indirectly. If you are looking for an absolute beginner's tutorial to help you get up to speed with programming in Python on your TI-84 Plus CE Python calculator, there's an excellent web site by Texas Instruments titled "10 Minutes of Code: Python". I strongly recommend taking a look at these skill building lessons. Here is the link: https://education.ti.com/en/activities/ti-codes/python/84 Whenever you find a command that looks a little mysterious, I strongly suggest you Google it for more information. In my opinion, this is a better way to learn a lot of Python programming techniques, by using and experiencing the commands in action. For example, it took me awhile to stumble upon Python's useful zip() function. I used it several places in the vectors program to create extremely concise and powerful vector functions. Do a Google search on "Python zip", learn how it works, and then you'll gain a really good understanding of how several of the vector functions work for 2d, 3d, or even bigger vectors. Any TI-84 calculator is a very powerful learning tool, but with the addition of Python in your TI-84 Plus CE Python calculator, its mindexpanding capabilities are truly awesome!
1. Calendar Functions How old are you today? Next time someone asks you this question, you can answer with the exact number of days rather than just rounding off to the number of years. Then, to impress them even more, be sure to casually mention the day of the week you were born. These are the types of questions the programs in this chapter will let you answer with ease.
CALENDAR
This program creates a nice one-month, single-page calendar for any month over a several-century period of time. At the heart of this program is a function that returns the Julian Day Number for any date in the range of years from 1582 to 4000. This function, named jd(), is explained in more detail later in this chapter, but here it is used to determine the number of days in any given month, and the day of the week for any date. From this information we can format all the days in a given month into an easy-to-read one-month calendar. Wilbur and Orville Wright's first heavier than air flight took place on the morning of December 17, 1903, at Kitty Hawk, North Carolina. We can run this program to see the full one-month layout of December, 1903 and easily determine that the 17th was a Thursday.
import ti_plotlib as plt
def jd(m,d,y): if m2: n=2 while n0 else b1+360 b2=b2 if b2>0 else b2+360 C=b1-b2 area+=area_sas(b,C,a) n+=1 return area
def nav(la1,lo1,la2,lo2): la1=radians(la1) lo1=radians(lo1) la2=radians(la2) lo2=radians(lo2) r=6371 t1=sin(la1)*sin(la2) t2=cos(la1)*cos(la2)*cos(lo2-lo1) km=acos(t1+t2)*r y=sin(lo2-lo1)*cos(la2) t1=cos(la1)*sin(la2) t2=sin(la1)*cos(la2)*cos(lo2-lo1) x=t1-t2 b=degrees(atan2(y,x)) return [b,km]
def area_sas(a,C,b): return a*b*sin(radians(C))/2
pts=gps_points() kmsq=round(area_gps(pts),6) print("Area") print("km^2: ",kmsq) misq=round(kmsq*.386102,6) print("miles^2: ",misq)
The second example calculates the surface area, very roughly, of Turquoise Lake, near Leadville, Colorado. Notice that you'll need to comment out the Pentagon data in the code listing, and un-comment the Turquoise Lake data. Here's a quick sketch (courtesy of Google Maps) of the area we'll find, as defined by four points I selected on the map:
The four map coordinates, starting at the bottom point and working around counter-clockwise, are: 39.249968, -106.370986
39.273513, -106.348860
39.277695, -106.438465
39.264220, -106.373614
I chose this lake, and this shape, on purpose, because there's a concavity at the bottom left, at the last coordinate, labeled 3:
The first triangle area is found at 0,1,2 as shown here:
Notice that this triangle is too big, covering more area than the overall lake outline. That's okay though, as the next triangle, at 0,2,3 is "backwards", in that the order of its points is clockwise instead of counter-clockwise, automatically resulting in a negative area.
No matter how complicated the list of coordinates gets, as long as they are in the correct "walk around" order for the entire polygon, all the areas add up correctly, both positive and negative, no matter how they overlap.
6.289 square kilometers is about 1,554 acres. A quick check on the Internet shows the area of Turquoise Lake to be 1,780 acres. Considering how crude our outline of the lake was, with just four points to define it, our calculation is pretty good! This program works well for land areas that aren't too large. The Earth is not flat, so the curve of the Earth's surface does affect calculated areas if they are very large, say hundreds of kilometers on edge.
GPS_DIST
Distance between two points in a plane is found using the Pythagorean Theorem, but distances on the surface of a sphere, such as the Earth, is more complicated. This program accurately calculates the distance between any two locations given their latitude and longitude coordinates, also referred to as GPS coordinates. The algorithm uses several trigonometric functions, so the math module is imported at the top of the listing. The sin() and cos() functions in Python assume all angles are in radians, so the radians() function in the math module is used to convert latitude and longitude from standard degrees to radians. (Yes, there is a degrees() function as well, but it's not used in this program.) The distance() function is at the heart of this program. Inputs are latitude and longitude for two points on the Earth, and output is the kilometers between the two points. The constant 6371 is the radius of the Earth in kilometers. For example, the Gateway Arch in St. Louis is visible on Google Maps, and we can carefully zoom in and click to find the coordinates at back corners of the Arch where the metal meets the concrete. Those are the pair of coordinates in the program listing. Another coordinate is at the Golden Gate Bridge in San Francisco, so we can measure a greater distance as well. The St. Louis Arch is officially 630 feet tall and 630 feet wide. This program calculates the width as 629.9 feet, which is probably more accurate than it should be, but I'll take it! The air (straight-line) distance between San Francisco and St. Louis is listed as 1745 km, and this program finds the distance between the Arch and the Bridge as 1744.7 miles, which is also an amazingly similar result:
from math import *
def distance(pt1,pt2): la1=radians(pt1[0]) lo1=radians(pt1[1]) la2=radians(pt2[0]) lo2=radians(pt2[1]) r=6371 t1=sin(la1)*sin(la2) t2=cos(la1)*cos(la2)*cos(lo2-lo1) km=acos(t1+t2)*r return km
#Arch width pt1=(38.625412,-90.184555) pt2=(38.623767,-90.185227) km=distance(pt1,pt2) print() print("Arch Meters:\n",km*1000) print("Arch Feet:\n",km*3280.84)
#Arch to Golden Gate Bridge pt2=(37.820142,-122.478709) km=distance(pt1,pt2) print() print("Arch-Bridge km:\n",km) print("Arch-Bridge miles:\n",km*.621371)
MIDPOINT
This program finds the latitude and longitude at a point halfway between two other locations on the Earth. Call up your friend a state or two away and have them meet you at the exact midpoint, just for fun. This program is also great for checking if the Earth is flat or round. Seriously. Consider that the Sun's elevation angle can be easily measured with a simple meter stick on a sunny day (see the program SUN_ELEV later in this book). I won't go into all the details here, but note that the elevation angle of the Sun as measured from three equidistant points on the Earth, will provide all the information you need. If the Earth is flat, the elevation angles will behave one way, and if the Earth is round the angles will behave another way. (Hint: it is round, but feel free to check for yourself an excellent way to discover the truth!) Let's find the latitude and longitude of the point halfway between the Golden Gate Bridge in San Francisco, and the Gateway Arch in St. Louis. Here's the location of one corner of the arch, as we used in the GPS_DIST program: la1=38.625412
lo1=-90.184555
And here's the Golden Gate Bridge coordinate from the same program: la2=37.820142
lo2=-122.478709
Let's plug those coordinates into the program, find the midpoint on the Earth, and then look up that point on Google Maps to see what's there:
The midpoint is in a very picturesque place along the West Tennessee Creek, just a little northwest of Leadville, Colorado. That would be a fun place to meet your friend!
from math import *
def mid(pt1,pt2): la1=radians(pt1[0]) lo1=radians(pt1[1]) la2=radians(pt2[0]) lo2=radians(pt2[1]) x=cos(la1)*cos(lo1) y=cos(la1)*sin(lo1) z=sin(la1) x+=cos(la2)*cos(lo2) y+=cos(la2)*sin(lo2) z+=sin(la2) la=degrees(atan2(z,(x*x+y*y)**.5)) lo=degrees(atan2(y,x)) return [la,lo]
pt1=(38.625412,-90.184555) pt2=(37.820142,-122.478709) pt3=mid(pt1,pt2) print("\nPoint1, Point2, Midpoint\n") print(pt1) print(pt2) print(pt3)
Note that the location coordinates are edited directly into the program listing, where assignments are made to the variables pt1 and pt2.
NAVIGATE
This program calculates the distance and bearing between any two points on the surface of the Earth. It's easy to find the location of a point on Earth using Google Maps. Zoom in to the location, right-click on the point, and select "What's Here?" from the popup menu. That's a good way to get the latitude and longitude numbers required as input for this program. The great circle route formula used here is accurate for short distances, such as measuring a short stretch of sidewalk in front of a school, and it's also accurate for much longer distances where the spherical shape of the Earth becomes very important. The location, or GPS coordinates taken from Google Maps, of Dulce, NM and Taos, NM are hard coded into the program to test it out. Feel free to change these numbers, or to change the program to have it prompt for inputs. The core functionality is in the nav() function, so call it any way that you wish. As shown, the distance from Dulce to Taos is very close to 140 km, and the direction to head is 114.3 degrees, or just a little south of due east.
from math import *
def nav(pt1,pt2): la1=radians(pt1[0]) lo1=radians(pt1[1]) la2=radians(pt2[0]) lo2=radians(pt2[1]) r=6371 t1=sin(la1)*sin(la2) t2=cos(la1)*cos(la2)*cos(lo2-lo1) km=acos(t1+t2)*r t1=cos(la1)*sin(la2) t2=sin(la1)*cos(la2)*cos(lo2-lo1) x=t1-t2 y=sin(lo2-lo1)*cos(la2) b=degrees(atan2(y,x)) return [b,km]
# Dulce, NM pt1=(36.9336,-106.9989)
# Taos, NM pt2=(36.4072,-105.5731)
# Distance and bearing b,km=nav(pt1,pt2)
print("\npt1: ",pt1) print("pt2: ",pt2) print("km: ",km) print("miles: ",km*.621371) print("bearing: ",b)
5. Money and Finances This chapter presents several programs to calculate interest, savings, loans and other details having to do with the flow of money. The next time you're ready to buy a car, or house, or game console, you can see how much the loan will cost you in interest, or better yet, how long it will take to save up to pay cash.
DEPOSITS
This short program helps you save for a goal by calculating how much money to put away in an interest bearing account, and for how long, in order to reach your goal. For example, perhaps you want to get a new gaming laptop that costs $1000, and you want it one year from today. As shown, you should start putting away $80.69 each month in an account if it earns 7% interest.
fv=float(input("\nDollars goal: ")) ir=float(input("Interest rate: ")) mo=float(input("Months: ")) ir/=1200 dp=fv/((ir+1)**mo-1)*ir s="\nMonthly deposits: ${:.2f}" print(s.format(dp))
FUTURVAL Saving up for something you want to purchase in the future is a great way to make your money go further. The money accumulates at some interest rate, instead of having to pay out interest on a loan, so you basically save in two ways. This program lets you experiment to see just how much you'll save, and to help you stay on target as you invest in yourself. You are prompted for the amount of money you can provide each month, the annual interest rate that the money will accumulate more value, and the number of years to tally the total. The future value is output. In the example shown, $50 is put away each month, at an accumulating annual interest rate of 7%, and the future value after 3 years, totalling $1996.50 is output.
dp=float(input("\nMonthly deposit: ")) ir=float(input("Interest rate: ")) yr=float(input("Years: ")) ir/=1200 mo=yr*12 fv=dp*((ir+1)**mo-1)/ir print("\nFuture value: ${:,.2f}".format(fv))
INTEREST
This program calculates the interest rate being charged for a loan when the principal, monthly payment amount, and the number of months to make the payments are known. The calculated annual interest rate is output. The example shows an annual percentage rate of 10.49% is being charged for a loan of $10,000 with monthly payments of $325 over a 3 year period, or 36 months.
p=float(input("\nPrincipal: ")) pmt=float(input("Monthly payments: ")) n=float(input("Months: ")) r,t=1,0 while t!=r: t=r r=pmt*((1+r)**n-1)/p/(1+r)**n i=round(r*1200,2) print("APR: {}%".format(i))
MONTHS
This program calculates the number of months required to pay off an amount of money, when the loan is accumulating interest charges. For example, you borrow $1,000 and agree to pay $25 each month at 7% interest. This program tells you that it will take 49 months. The number of months is rounded off to the nearest whole month. The good news is the last payment will likely be less than the rest of the payments.
p=float(input("\nPrincipal: ")) r=float(input("Annual Interest: "))/1200 pmt=float(input("Monthly payments: ")) n,d=0,pmt+1 while d>pmt: n+=1 d=round(p*(r*(1+r)**n)/((1+r)**n-1),2) print("Months: ",n)
PAYMENTS
This program calculates monthly payments for a loan given the amount, or principal of the loan, the annual percentage rate, and the number of monthly payments to be made. The example shows a loan of $5000 at 9% interest rate will require 24 monthly payments of $228.42.
p=float(input("\nPrincipal: ")) r=float(input("Annual Interest: "))/1200 n=float(input("Months: ")) pmt=p*(r*(1+r)**n)/((1+r)**n-1) pmt="${}".format(round(pmt,2)) print("Monthly payments: ",pmt)
PRNCIPAL
Given the monthly payment amount for a loan, the annual percentage rate for the loan, and the number of months to pay the loan off, this program calculates the original principal of the loan. For example, given payments of $228.42 monthly for 24 months at 9% interest, the original loan amount was $4999.92. The actual amount of the loan was probably $5000, because slight roundoff errors can accumulate to a few cents pretty easily, as in this case.
pmt=float(input("\nMonthly payments: ")) r=float(input("Annual Interest: "))/1200 n=float(input("Months: ")) p=pmt/(r*(1+r)**n)*((1+r)**n-1) p="${}".format(round(p,2)) print("\nPrincipal: ",p)
6. Numerical Calculations The programs in this chapter cover a lot of the standard calculations that calculators and computers can do, and that you might find useful for your studies or on the job. The programs vary from a fast way to find prime numbers, to solving simultaneous equations, finding roots of equations, providing a complete set of vector functions, and more.
BINHXDEC
Computers use bits and bytes and numbers in hexadecimal and binary format all the time. This program shows how a number can easily be converted to and from any of these formats. For example, the hexadecimal number 0x4DF3 is the same as decimal 19955, and it's the same as the binary number 0b100110111110011. The program asks for input in any one of the formats, and all three formats are displayed as output:
Note that there's an even simpler way to convert hexadecimal or binary numbers to decimal. In the shell, at the >>> prompt simply enter the value, making sure you add the appropriate prefix of either "0x" or "0b". The decimal value will be displayed. To convert in the other direction, from decimal to the other two formats, this program does the trick. Hexadecimal values can be entered in either upper or lower case.
The last few lines of the program show how to format a decimal integer for output in all three number formats. print("\nInput one of the following") print("0bnn.. binary") print("nn..decimal") print("0xnn.. hexadecimal") n=input("\nNumber? ").lower() if n[0]=="0": if n[1]=="b": n=int(n[2:],2) elif n[1]=="x": n=int(n[2:],16) else: n=int(n) print() print("Hex: ","0x{:X}".format(n)) print("Bin: ","0b{0:b}".format(n)) print("Dec: ",n)
BINSRCH
This program finds roots of a function, or where the function crosses the x-axis at y=0. Edit your function of x in the appropriately named function f(x), at the top of the listing. Here's the function we'll work with in the example:
One way to calculate a power of x in Python is with two asterisks, and that's what we'll use in the example. (The other way is to use the pow() function in the math library.) def f(x): return 0.7*x**3-7*x**2+3*x+17
A quick plot of this function on your TI-84 Plus CE Python calculator (not using Python) shows the function has three roots that lie somewhere between -5 and +15 on the X axis. This program will help you find those roots fast and efficiently.
The roots() function in this Python program is passed three values; the starting x value for the interval to check, the ending x value, and the number of steps to take between them. The number of steps should be sufficient that a zero-crossing of the function won't be "stepped over". 100 works well in most cases. If there's one or more roots in the designated interval, they will be returned. In this example, since we know the three roots are between -5 and +15 (the edges of the graph), the roots() function is called like this: roots(-5, 15, 100), and the three returned roots are printed on the display.
The roots() function breaks down the large interval into many smaller intervals, based on the step size argument. The function is called for the end points of these smaller intervals. Whenever the two returned values don't have the same sign, the function root() is called to use a binary search to find the "exact" root in that interval. The binary search cuts the interval between x1 and x2 in half, calculates y at that midpoint, then determines if a root must lie somewhere to the left or to the right of that midpoint. The value of x1 is replaced with the midpoint value in one case, and x2 is replaced otherwise. The search is repeated within this tighter interval, over and over, until the difference between x1 and x2 approaches zero, at the root value of x. Edit the function at the top of the listing, and the call to roots() at the end of the listing to find roots for your own functions. def f(x): return 0.7*x**3-7*x**2+3*x+17
def roots(xmin,xmax,steps):
inc=(xmax-xmin)/steps while xmin=xmin: print(x) xmin+=inc
def root(x1,x2): dif=0 y1=f(x1) y2=f(x2) while 1: if y1*y2>0: return x1-1 x=(x1+x2)/2 y=f(x) if y1*y>0: x1=x y1=f(x1) else: x2=x y2=f(x2) if x1-x2!=dif: dif=x1-x2 else: return x
roots(-5,15,100)
Note that the program NEWTON later in this chapter finds roots in a very similar, but often much faster way.
FACTORS
This program finds all the factors of an integer. The factors() function is passed an integer, and it returns a list of all its prime factors. For example, the prime factors of 16 are four 2s, the prime factors of 12345 are 3, 5, and 823, and the prime factors of 123454321 are 41, 41, 271, and 271:
When I first created this program, the factors were found by dividing by all numbers from 2 to the given number to find those that would divide evenly. This worked great for relatively small integers, but it slowed way down for numbers in the tens of thousands or greater. To speed things up (a lot!) I borrowed the next_prime() and is_prime() functions from elsewhere in this book, checking for divisibility by prime numbers, and only up to the square root of the given integer. This added a little length to the code listing, but the much speedier results were worth it.
def factors(n): factlist=[] m=2 while n>1: if n%m==0: factlist.append(m) n//=m else: m=next_prime(m) if m*m>n: factlist.append(n) break return factlist
def next_prime(n): p=n+1 while not isPrime(p): p+=1 return p
def isPrime(n): primes = ( 2,3,5,7,11,13,17,19,23,29,31,37,41, 43,47,53,59,61,67,71,73,79,83,89,97) if n in primes: return True for m in primes: if n%m==0: return False for m in range(primes[-1]+2,n//m+1,2): if n%m==0: return False return True
n=int(input("\nEnter n: ")) print(factors(n))
FIBONACC
The fibonacci sequence is fascinating, and this program lets you explore its features interactively. Starting with a list of any two integers (other than both zeros), where zero and one are often what are chosen, if you add them together to add to the list, then add the last two numbers on that list to get the next, and so on, you quickly end up with a ratio between the last two numbers on the list that approaches the golden ratio. Search the Internet to learn more about the golden ratio, as there are a lot of curious facts where the explanation at first doesn't seem reasonable. For example, the golden ratio is exactly the same as 2 * sin(54 degrees). The reason has to do with a pentagon shape, but I'll let you discover those details for yourself. Another interesting fact is that you don't need to start with 0 and 1 to form a Fibonacci sequence. In fact, you can start with any two numbers, positive or negative, integer or float, and the ratio of the last two numbers on the list will quickly approach the golden ratio. That's weird. And you've just got to try it! Here's the result of starting with 0 and 1, and iterating to grow the sequence 20 times.
As you can see, the ratio of 10946 to 6765 is very close to the golden ratio. (The golden ratio can also be calculated as one plus the square root of five all divided by two, and that's how the more exact value is calculated in the last line of the output.) Next, start with -17.85 and 97.65. After just 20 additions the ratio can also be seen to be quickly approaching the golden ratio:
a=float(input("\nEnter a: ")) b=float(input("Enter b: ")) n=int(input("Number of additions: ")) for i in range(n): a,b=b,a+b print() print("a: ",a) print("b: ",b) print("a / b: ",a/b) print("b / a: ",b/a) print("Golden: ",(1+5**.5)/2)
GCD_LCM
This program finds the GCD (greatest common divisor) and the LCM (least common multiple) of two integers. The GCD of two integers is the largest positive integer that divides evenly into both. The LCM of two integers is the smallest positive integer that is a multiple of both. It turns out that the product of the two original numbers is the same as the product of the LCM and the GCD. For example, given the integers 24 and 56, we find their GCD is 8, and their LCM is 168.
def gcd(a,b): while 1: c=a-b*int(a/b) a,b=b,c if not c: return a
def lcm(a,b): return int(abs(a*b/gcd(a,b)))
a=int(input("\nEnter a: ")) b=int(input("Enter b: ")) print("\nGCD: ",gcd(a,b)) print("LCM: ",lcm(a,b))
GLDRATIO
Search on the Internet for fascinating information about the Golden Ratio (GR), and you'll discover there are multiple ways to calculate this number. Perhaps the most direct calculation is to use this formula:
Another way to calculate GR is with the Fibonacci Sequence (see the FIBONACC program earlier in this chapter.) In this program a very simple iteration starts with any number and it fairly quickly converges on the value of the Golden Ratio. The GR is equal to 1 + 1/GR, which provides a slick way to iterate to its value. For example, starting with the number -123.4567 the GR is found after just 40 iterations:
print("\nEnter any non-zero number: ") x=float(input("? ")) y,n=0,0 while x!=y: x,y,n=1+1/x,x,n+1 print("\nIterations: ",n) print("Golden: ",x) print("Exact: ",(1+5**.5)/2)
NEWTON
The BINSRCH program found the roots of a function f(x) using a binary, "split in half" search algorithm. This program also finds roots of a function of x, but it uses Newton's method, a really cool algorithm that in many cases finds roots extremely efficiently. Newton's method is an iterative method that uses the slope of the function (also known as the first derivative) to help aim at where the function crosses the x axis. Here's the formal definition, where f'(x) is the slope, or derivative, of f(x).
To demonstrate this program, we'll find the three roots of the same function of x as in the BINSRCH program:
A quick sketch of this function in your TI-84 Plus CE Python calculator shows there are three roots between -5 and +15 along the x axis.
The NEWTON program calls the roots() function just like in the BINSRCH program, passing the limits of an interval along the x axis to search, and the number of steps for checking subintervals.
def f(x): return 0.7*x**3-7*x**2+3*x+17
def slope(x): dx=0.0001 dy=f(x+dx)-f(x) return dy/dx
##def slope(x): ## return 2.1*x*x-14*x+3
def roots(xmin,xmax,steps): inc=(xmax-xmin)/steps for i in range(steps): root(xmin,xmin+inc) xmin+=inc
def root(x1,x2): if f(x1)*f(x2)