-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic.py
41 lines (37 loc) · 1.95 KB
/
logic.py
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
def ln(number, *, precision=20):
"""
This function calculates the natural logarithm of a number using the properties of logarithms and the Taylor series.
The input number is decomposed into a product of a scaling factor and a power of two using the decomposer function.
The Taylor series is then used to calculate the natural logarithm of the scaling factor, and the natural logarithm of the power of two is added to this result.
"""
exponent, scalingFactor = decomposer(number)
def HornersScheme(num):
output = 0
for iteration in range(precision, 0, -1):
output = num * (1 / iteration - output)
return output
return exponent * 0.6931471805599453 + HornersScheme(scalingFactor - 1)
def decomposer(number):
"""
Decomposes the input into a power of two if it's larger than 1/2.
"""
exponent = 0
while (abs(number) > 1):
number /=2
exponent += 1
return exponent, number
def lnOptimized(num, *, precision=20):
"""
Computes the natural logarithm. [precision] determines the number of terms included in the Taylor series to approximate
the ln function.
"""
fraction = (num - 1) / (num + 1)
return sum([2 / (2 * n + 1) * fraction**(2 * n + 1) for n in range(precision)])
def logBase(number, base, *, precision=20):
"""
This function calculates the logarithm of a number to any base using the properties of logarithms and the Taylor series.
The input number is decomposed into a product of a scaling factor and a power of two using the decomposer function.
The Taylor series is then used to calculate the natural logarithm of the scaling factor, and the natural logarithm of the power of two is added to this result.
Finally, it uses the change of base formula to calculate the logarithm to the desired base.
"""
return lnOptimized(number, precision=precision) / lnOptimized(base, precision=precision)