1
votes

Now, just before you start downvoting this question let me explain something, I'm pretty young and trying to learn python. I don't have any resources at all in school to learn this kind of math.

I am doing an exercise which says this:

Write a function called myPi that will return an approximation of PI (3.14159...). Use the Leibniz approximation. Located here: http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

So, they show how to calculate it like this: http://upload.wikimedia.org/math/9/e/8/9e804b8a1a11e442be93fed1d52205a9.png

I have no idea how to calculate this in python. I mean, I don't even know how to calculate it normally since how would I calculate something that goes on infinite?

Also, another question is. Do I really need such advanced math to write programs later? Many of my friends learned to program while they were 12/13 and they had no problems. So is advanced math that important? Since I doubt my friends even knew how to calculate the area of a circle when they were learning.

3
In any case maths any computer science are strongly related..if you are interested in programming you slould really have a good background in maths - apomene
The key to your 'goes to infinity problem' is the the use of the word 'approximation'. The exact solution is an infinite sum. Since you cannot calculate an infanite sum, you must settle for an approximation, which is a finite sum. In other words if you stop that some at an arbitrary point you will be left with an approximation of π/4, which you then solve for π - aruisdante
To answer your second question, while knowledge of mathematics is definitely useful for programming, there are many, many tasks that programmers do that don't require more than basic algibra (you'll at least need algibra, most programming language symantics borrow pretty heavily from algibraic notation). You just happened to pick a problem that had some math beyond your experience, but there are many many problems that require no real math at all. - aruisdante
@aruisdante Whats the logic behind that though? I mean, pi/4 would give me 1/4th of PI. Don't I want all of pi? Can you show me code that would do what it asks for? Seeing some code would probably make it easier for me to understand. - Czarek
@aruisdante I do understand algebra, that isn't a problem so I guess I am good? - Czarek

3 Answers

5
votes

To address your first question, "how do you calculate an infinite series", the answer is to approximate it, usually using either:

  1. A defined number of steps ("I want it to take this long"); or
  2. Until the change at each step falls below a specified tolerance ("I want it to be this accurate").

To illustrate these (there is some relatively advanced Python here - leibniz_series is a generator to remove some duplicated code between the two implementations, it just churns out the terms in the series as long as you keep asking for them):

def leibniz_series():
    """Generator producing the Leibniz series (1, -1/3, 1/5, -1/7, ...)."""
    numerator = denominator = 1.0
    while True:
        yield (numerator / denominator)
        numerator *= -1
        denominator += 2

def pi_steps(steps=100):
    """Calculates pi from the Leibniz series with a defined number of steps."""
    values = leibniz_series()
    output = 0
    for _ in range(steps):
        value = 4 * next(values)
        output += value
    return output

def pi_tolerance(tolerance=0.0001):
    """Calculates pi from the Leibniz series with a defined output tolerance."""
    values = leibniz_series()
    output = 0
    value = 4 * next(values)
    while abs(value) > tolerance:
        output += value
        value = 4 * next(values)
    return output

As to the second question, "do you need to know ('advanced') maths to program", the answer really is "it depends what you're doing". Do you want to write a game with a physics engine? That would be very difficult to do without the equations of motion! But there are other things you can do with little more than the addition and subtraction required to deal with indexing into lists etc.

This specific exercise is more about using the software to carry out a repetitive task than it is about actually calculating pi (which is available as math.pi anyway!) Don't worry if you don't fully understand that maths at this stage; what is important is being able to understand the task (sum over some of the Leibniz series, multiply the result by 4) and how to break that down to steps you can represent in code.

3
votes

Given that @jonrsharpe already provided a solid answer on the specific problem, I'd like to add some additional information on learning Python or any language in general, and how much math may be necessary.

Many tutorials teach programming by recreating problems with known solutions, a method often considered "reinventing the wheel" or "reimplementing the wheel". This strategy will teach you how to solve a given problem and how to approach problems with similar nature.

However in order to make for a productive learning process you should focus on problems that you can reason about or for which you can visualize a way towards a solution. Otherwise you will get lost between the two things that you will need to learn: the tool (programming language) and the strategy (in this case, using math).

My suggestion, think of something that you want to do. Start with simple tasks like reading text files, parsing and transforming text, or small games like tic-tac-toe, hangman, simon and other memory games. Then break the problem into smaller problems that you can solve. For instance, you may not know how to draw a tic-tac-toe board, so first you would learn how to draw a line and a circle. Then you may not know how to make the computer smart and have it play against you, so instead make the game so you play against another person, and so on.

If you are just starting with programming, have a look at the exercises from Code Club. They are somewhat basic but still challenging.

Once you feel comfortable with the Python language, start looking at code written by other people. Since Python modules are generally open-source, you can search for any topic you might find interesting at PyPi and study how other people solved the problem.

If at any point you feel lost, you can also join the #Python channel on the Freenode IRC network where, with some patience, you will find someone willing to help you and give you some guidance.

1
votes

To actually solve the problem, consider the following:

The fraction portion of the sum is:

-1/3+1/5-1/7+1/9 ...

What is the pattern here? Well, first the sign obviously alternates every number. Next, the denumerator starts at 3 and then adds 2 to it every iteration. This, when combined with the initial value of 1 leads us to the mathematical sum that is represented on the wiki page,

Sum(-1^n/(2n+1))

How to express this in code?

Well, in 99% of programming languages, if you are trying to express a sum, which is a formula that is based on some input number (n), and then added to itself with the value calculated at (n+1), you should think for loop . in python, we can express that sum as so:

def approximate_pi(iterations):
    sum = 0
    for n in range(iterations):
        sum += (-1)**n/(2*n+1)
    return sum*4

This will, given a finite number of iterations, calculate an approximation of the value of π. The bigger iterarions, the more accurate the result will be, at the cost of increased run time.

Python, however, has some shortcuts that make this even easier. The first is the built in function sum, which returns the result of adding together the numbers in a list. The next is a list comprehension, which produces a list from some input arguments. This simplifies our original function to the following:

approximate_pi(iterations):
    return 4*sum([(-1)**n/(2*n+1) for n in range(iterations)])

This is doing basically the same series of operations, just in a way that's more efficient for python (for loops are expensive i n python) and that actually looks closer to the original pure mathematical notation.