Maths Functions - Python

From TRCCompSci - AQA Computer Science
Revision as of 08:57, 21 June 2018 by Admin (talk | contribs) (Statistical Functions)
Jump to: navigation, search

Standard arithmetic can be performed without any additional code (ie -+/*%). However you can extend this by importing some of the default modules installed with python. These are math, random, statistic, decimal and fraction:

Math Functions

A range of mathematical functions is available from math module of the standard library:

import math #import the math module

print math.sin(10)       # sine
print math.cos(10)       # cosine
print math.tan(10)       # tangent 

print math.asin(10)      # arc sine
print math.acos(10)      # arc cosine
print math.atan(10)      # arc tangent

print math.sinh(10)      # hyperbolic sine    
print math.cosh(10)      # hyperbolic cosine
print math.tanh(10)      # hyperbolic tangent

print math.pow(2, 4)     # 2 raised to 4
print math.exp(4)        # e ^ 4
print math.sqrt(10)      # square root
print math.pow(5, 1/3.0) # cubic root of 5
print math.log(3)        # ln; natural logarithm
print math.log(100, 10)  # base 10

print math.ceil(2.3)    # ceiling
print math.floor(2.7)   # floor

print math.pi
print math.e

Random Functions

Pseudo-random generators are available from the random module:

import random #import the random module
print random.random()     # Uniformly distributed random float >= 0.0 and < 1.0.
print random.random()*10  # Uniformly distributed random float >= 0.0 and < 10.0
print random.randint(0,9) # Uniformly distributed random int >= 0 and <=9
li=[1, 2, 3]; random.shuffle(li); print li # Randomly shuffled list

Decimal Functions

The decimal module enables decimal floating point arithmethic.

import decimal #import the decimal module
plainFloat = 1/3.0
print plainFloat # 0.3333333333333333
decFloat = decimal.Decimal("0.33333333333333333333333333333333333333")
print decFloat   # Decimal('0.33333333333333333333333333333333333333')
decFloat2 = decimal.Decimal(plainFloat)
print decFloat2  # Decimal('0.333333333333333314829616256247390992939472198486328125')

Fraction Functions

Compared to floating point numbers representing fractions, Fraction fractions do not lose precision.

from fractions import Fraction #import the fraction module
oneThird = Fraction(1, 3)
floatOneThird = 1/3.0
print Fraction(0.25)                  # 1/4
print Fraction(floatOneThird)         # 6004799503160661/18014398509481984
print Fraction(1, 3) * Fraction(2, 5) # 2/15

Statistical Functions

Python also has built in statistical fucntions:

import statistics as stats #import the statistics module
print stats.mean([1, 2, 3, 100]) # 26.5
print stats.median([1, 2, 3, 100]) # 2.5
print stats.mode([1, 1, 2, 3]) # 1
print stats.pstdev([1, 1, 2, 3]) # 0.82915...; population standard deviation
print stats.pvariance([1, 1, 2, 3]) # 0.6875; population variance