I have a quite puzzling issue that I suspect has to do with scientific notation and decimal precision. Here is part of my code:
def atan(x):
# Calculate arctan(1/x)
x = Decimal(x)
current_value = Decimal(0)
divisor = 1
x_squared = x * x
current_term = 1 / x
while True:
current_value += current_term
divisor += 2
current_term = (-current_term / x_squared) / divisor
print(current_term)
# The issue
if current_term == Decimal(0):
break
return current_value
print(atan(5))
This is based on the formula atan(1/x) = 1/x - 1/(3x^3) + 1/(5x^5) - ...
However, I discovered that current_term, which gets smaller every loop iteration, is going into values like 4E-80000. Since I've set my decimal precision getcontext().prec to 20, current term should not even support these values. I think somehow current_term is not of decimal type but of scientific notation/float type, but python tells me it's still decimal type.
The correct value for arctan(1/5) is about 0.1973955. I get a value of 0.1973545, which is wrong starting at the 5th digit. Even if I manually break the loop the value is still wrong for some reason. Any help fixing this issue is appreciated.
Decimalwouldn't be floating point values but fixed point values.4E-80000==Decimal(0)should return True (I tested it)