0

def factorial(n):
    if n == 1:
        return n
    else:
        return n*factorial(n-1)


def sin(x):
    OddNumber = 3
    counter = 1
    NumberOfTerms = 80
    while counter < NumberOfTerms:
        x -= (x**OddNumber)/(factorial(OddNumber))
        OddNumber += 2
        counter += 1
        x += (x**OddNumber)/(factorial(OddNumber))
        OddNumber += 2
        counter += 1
    return x


theta = float(input("input angle in degrees: "))
theta = float((theta*math.pi/180))
print(sin(theta))

This is the code I'm using to try to find the approximation of sin of an angle x. I want to increase the variable NumberOfTerms to increase the precision but when I do i get this error

OverflowError: int too large to convert to float

How can I get around this? Is there a way to get around this?

  • 1
    Does this answer your question? [OverflowError: long int too large to convert to float in python](https://stackoverflow.com/questions/16174399/overflowerror-long-int-too-large-to-convert-to-float-in-python) – Jan Christoph Terasa Apr 09 '21 at 13:47
  • @JanChristophTerasa on line 16 how do I make it convert to decimal and not to float? – Hallojvjknvve Apr 09 '21 at 13:50
  • 3
    Seem you are implementing `sin` with Taylor series. Note that you may not need that many terms because floating number in computer have only about 15 decimal sigificants digits (53 binary digits). This means, if `abs(n-th term / 1st term) < 10 ** -15` (or `2 ** -53`), the n-th term do not change the result. – Aaron Apr 09 '21 at 14:08
  • @Aaron I am trying to do that but this code only works if the number of "steps" is 80 which is not equal to the value (according to google) so how do I increase the number of "steps" – Hallojvjknvve Apr 09 '21 at 14:23

1 Answers1

0

When you use the reciprocal factorial value the code works fine with higher NumberOfTerms

import math

def reciproc_factorial(n):
    if n == 1:
        return n
    else:
        return 1/n*reciproc_factorial(n-1)


def sin(x):
    OddNumber = 3
    counter = 1
    NumberOfTerms = 150
    while counter < NumberOfTerms:
        x -= (x**OddNumber) * (reciproc_factorial(OddNumber))
        OddNumber += 2
        counter += 1
        x += (x**OddNumber) * (reciproc_factorial(OddNumber))
        OddNumber += 2
        counter += 1
    return x


theta = 23
theta = float((theta*math.pi/180))
print(sin(theta))
Stefan Fenn
  • 483
  • 5
  • 13