forked from SeattleTestbed/seattlelib_v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath.repy
63 lines (49 loc) · 1.75 KB
/
math.repy
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
""" Justin Cappos -- substitute for a few python math routines"""
def math_ceil(x):
xint = int(x)
# if x is positive and not equal to itself truncated then we should add 1
if x > 0 and x != xint:
xint = xint + 1
# I return a float because math.ceil does
return float(xint)
def math_floor(x):
xint = int(x)
# if x is negative and not equal to itself truncated then we should subtract 1
if x < 0 and x != xint:
xint = xint - 1
# I return a float because math.ceil does
return float(xint)
math_e = 2.7182818284590451
math_pi = 3.1415926535897931
# Algorithm from logN.py on
# http://en.literateprograms.org/Logarithm_Function_(Python)#chunk
# MIT license
#
# hmm, math_log(4.5,4) == 1.0849625007211561
# Python's math.log(4.5,4) == 1.0849625007211563
# I'll assume this is okay.
def math_log(X, base=math_e, epsilon=1e-16):
# JMC: The domain of the log function is {n | n > 0)
if X <= 0:
raise ValueError, "log function domain error"
# log is logarithm function with the default base of e
integer = 0
if X < 1 and base < 1:
# BUG: the cmath implementation can handle smaller numbers...
raise ValueError, "math domain error"
while X < 1:
integer -= 1
X *= base
while X >= base:
integer += 1
X /= base
partial = 0.5 # partial = 1/2
X *= X # We perform a squaring
decimal = 0.0
while partial > epsilon:
if X >= base: # If X >= base then a_k is 1
decimal += partial # Insert partial to the front of the list
X = X / base # Since a_k is 1, we divide the number by the base
partial *= 0.5 # partial = partial / 2
X *= X # We perform the squaring again
return (integer + decimal)