-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
51 lines (44 loc) · 1.31 KB
/
utils.py
File metadata and controls
51 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# utils.py
# Math library
# Author: Sébastien Combéfis
# Version: February 8, 2018
import math
from scipy.integrate import quad
import numpy
def fact(n):
"""Computes the factorial of a natural number.
Pre: -
Post: Returns the factorial of 'n'.
Throws: ValueError if n < 0
"""
if n<0:
return ValueError
else:
return math.factorial(n)
def roots(a, b, c):
"""Computes the roots of the ax^2 + bx + x = 0 polynomial.
Pre: -
Post: Returns a tuple with zero, one or two elements corresponding
to the roots of the ax^2 + bx + c polynomial.
"""
return numpy.roots((a, b, c))
def integrate(function, lower, upper):
"""Approximates the integral of a fonction between two bounds
Pre: 'function' is a valid Python expression with x as a variable,
'lower' <= 'upper',
'function' continuous and integrable between 'lower‘ and 'upper'.
Post: Returns an approximation of the integral from 'lower' to 'upper'
of the specified 'function'.
Hint: You can use the 'integrate' function of the module 'scipy' and
you'll probably need the 'eval' function to evaluate the function
to integrate given as a string.
"""
if lower <= upper:
res, err = quad(lambda x:eval(function),lower,upper)
return res
else:
pass
if __name__ == '__main__':
print(fact(5))
print(roots(1, 0, 1))
print(integrate('x ** 2 - 1', -1, 1))