Saturday, June 20, 2020

Math

Math


There are ceiling and floor functions that find the nearest integer, i.e., math.ceil(1.49), math.ceil(1.45) math.ceil(1.44) will all give you a return value of 2.  math.ceil(-1.49) gives -1. 

It appears that the square root function when you import the math module will not take or return complex numbers.

The pow() function however, will accept arguments that lead to complex numbers. It returns the machine epsilon though instead of zero.

# the square root of -4
x = pow(-4,0.5) ###  gives 1.22E16 + 2j

 

Other interesting math functions that you don't normally see built into other languages are the combination and permutation functions, sum over iterables, product over iterables, and isclose() with two arguments to determine distance between numbers.

import math

c = math.comb(4,2) 

# the number of unordered non-repeating pairs among 4 different things

print(c)

# 4!/((4-2)! * 2!)

GIVES A RESULT OF 4

import math
c = math.perm(4,2)
# ordered non-repeating pairs among 4 different things

print(c)

# 2^4

GIVES A RESULT OF 16



pennies_in_jars = (37, 56, 9, 105)

money = math.fsum(pennies_in_jars)

print(money)

# results in - note that fsum returns a float:

207.0



math.isclose(a, b, relative_tolerance = value, absolute_tolerance = value)

Default value is 1e-09 for relative_tolerance 

absolute_tolerance is needed for when numbers are very close to zero. It's value must be at least zero.

metric: Is abs(a-b) <= max( relative_tolerance * max(abs(a), abs(b)), absolute_tolerance ) ??


isclose() returns a boolean. You must use the exact phrases rel_tol and abs_tol to specify the values in the function call.

example

a = 1.35
b = 1.65

c = abs(a-b) # equals 0.3

rel_tol = 1E-09
abs_tol = 0.4

## 1E-09 * max(1.35, 1.65) = 1E-09 * 1.65 =  1.65E-09

## max(1.65E-09, 0.4) = 0.4

## Finally, is 0.3 < 0.4 # True

result = math. isclose(1.35, 1.65, rel_tol = 1E-09, abs_tol = 0.4)

#result is 

True



No comments:

Post a Comment