Processing math: 100%

CPSC120B
Fundamentals of Computer Science I

Lab 7

Range

Loop Game

Complete the third level of the Loop Game.

Challenge

Complete the fourth level of the Loop Game.

Leibniz Approximation

The mathematical constant π is an irrational number that represents the ratio between a circle's diameter and its circumference. The first algorithm designed to approximate π was developed by Archimedes in 250 BC, and was able to approximate its value within 3 significant figures. Today we know that there are an infinite number of digits in π, so lets use a little more sophisticated approach to estimate its value.

Details

Create the program in a file called leibniz.py. This function asks the user to input an integer, which is the number of terms to compute in the infinite series. It should use this value to compute the Leibniz approximation, discussed below.

The Leibniz approximation relies on the fact that:

π4=1113+1517

Which can be rewritten to approximate the true value of π:

π=4143+4547

Make sure to test your program by running it multiple times with different inputs. Make sure your code follows the course's code conventions.

Example

  $python3 leibniz.py
  How many terms? 1000
  3.140592653839794

Hint

Challenge

The value you get from the Leibniz formula will be incredibly close. However, it will never meet the true definition of π. To see how close it does get, compute the approximations for all equations from length 1 to length 1000. For each approximation, subtract the value of math.pi from it to compute the error. Sum up all of these errors, and print the average error.

Curve

Computer displays are made up of a grid of tiny lights. Because the displays are not continuous, curved objects must be broken into many non-continuous pieces. So curves are often simply represented as many straight lines. In this activity you will approximate a curve by drawing many lines.

Details

In Emacs, create a Python program in a file called curve.py. Your program should use the turtle module to draw a curve using overlapping straight lines between the x-axis and the y-axis.

Do not hard code the location of the line segment end points. Your program should have a variable that determines the size of the drawing. Your program should calculate the end point locations based on the size variable. Make sure you use proper variable names and follow the courses code conventions.

Example

$ python3 curve.py
Turtle Graphics Curve Made From Lines

Hint

Challenge

This same technique can be used to draw a myriad of different curves, by changing the length and angle of the axes. Add variable to your program that specify the length and angle of each of the axes to create curves like the following.

Turtle Graphics Obtuse Angle Curve Made From Lines

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.