-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
86 lines (67 loc) · 2.03 KB
/
utils.py
File metadata and controls
86 lines (67 loc) · 2.03 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Math library
# Author: Sébastien Combéfis
# Version: February 2, 2016
def fact(n):
"""Computes the factorial of a natural number.
Pre: -
Post: Returns the factorial of 'n'.
Throws: ValueError if n < 0
"""
try:
if type(n) != int or n < 0:
raise ValueError
i = n
result = 1
while i > 0:
result = result * n
i -= 1
return result
except ValueError:
print("n is not valid")
def roots(a, b, c):
"""Computes the roots of the ax^2 + bx + c = 0 polynomial.
Pre: -
Post: Returns a tuple with zero, one or two elements corresponding
to the roots of the ax^2 + bx + c polynomial.
"""
try:
delta = b**2-4*a*c
if a == 0 or delta < 0:
if b != 0 and delta >= 0:
result = -c/b
return (result,)
else:
return ()
elif delta > 0:
result1 = (-b + delta**(1/2))/(2*a)
result2 = (-b - delta**(1/2))/(2*a)
answer = (result1, result2)
return answer
elif (delta == 0):
result = (-b)/(2*a)
answer = result,
return answer
except:
print("An error has occured")
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'.
"""
h = float(upper - lower)/1000
s = 0
x = lower
s += eval(function)/2
for i in range(1, 1000):
x = lower + i*h
s+= eval(function)
x = upper
s += eval(function)/2
return s * h
if __name__ == '__main__':
#print(fact(-4))
print(roots(0, 0, 4))
#print(integrate('x ** 2 - 1', -1, 1))