How to do a Sigma in python 3

How to do a Sigma in python 3

A sigma (∑) is a Summation operator. It evaluates a certain expression many times, with slightly different variables, and returns the sum of all those expressions.

For example, in the Ballistic coefficient formula


The Python implementation would look something like this:

# Just guessing some values. You have to search the actual values in the wiki.
ballistic_coefficients = [0.3, 0.5, 0.1, 0.9, 0.1]

total_numerator = 0
total_denominator = 0
for i, coefficient in enumerate(ballistic_coefficients):
    total_numerator += 2**(-i) * coefficient
    total_denominator += 2**(-i)
print(Total:, total_numerator / total_denominator)

You may want to look at the enumerate function, and beware precision problems.

The easiest way to do this is to create a sigma function the returns the summation, you can barely understand this, you dont need to use a library. you just need to understand the logic .

def sigma(first, last, const):
    sum = 0
    for i in range(first, last + 1):
        sum += const * i
    return sum

# first : is the first value of (n) (the index of summation)
# last : is the last value of (n)
# const : is the number that you want to sum its multiplication each (n) times with (n)

How to do a Sigma in python 3

An efficient way to do this in Python is to use reduce().

To solve

Σ i

You can use the following:

from functools import reduce
result = reduce(lambda a, x: a + x, [0]+list(range(1,3+1)))

reduce() will take arguments of a callable and an iterable, and return one value as specified by the callable. The accumulator is a and is set to the first value (0), and then the current sum following that. The current value in the iterable is set to x and added to the accumulator. The final accumulator is returned.

The formula to the right of the sigma is represented by the lambda. The sequence we are summing is represented by the iterable. You can change these however you need.

For example, if I wanted to solve:

Σ π*i^2

For a sequence I [2, 3, 5], I could do the following:

reduce(lambda a, x: a + 3.14*x*x, [0]+[2,3,5])

You can see the following two code lines produce the same result:

>>> reduce(lambda a, x: a + 3.14*x*x, [0]+[2,3,5])
>>> (3.14*2*2) + (3.14*3*3) + (3.14*5*5)

Leave a Reply

Your email address will not be published. Required fields are marked *