Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sinus Approx
#1
Hi everyone,
im tryna write a program that prints an Approx of a sinus(x) using this:
sinus(x)=x-((x**3)/3!)+((x**5)/5!)-((x**7)/7!)+...

so in my code it doesnt even enter the while.
x=float(input())
res=x
from math import sin
v=sin(x)
sign=1
puis=1
s=1
while(v>res):
    puis=puis+2
    sign=sign*(-1)
    for i in range(puis):
        s=s*i
    res=res+(sign*(x**puis)/s)
print(res)
Reply
#2
It depends on what you input. The input has to be less than the sin of the input, since that is what the while loop tests the first time it is checked. If you enter 3, it obviously won't do anything, since sin is on the range -1 to 1. However, if you enter -0.1, it does something. Unfortunately that something is a ZeroDivision error.

The error comes from your for loop. The range function with just one input (puis) gives the numbers 0 to puis - 1. Since you are building a product there, 0 times anything is 0 and s is always 0. If you are trying to calculate the factorial of puis there, use range(1, puis + 1) to get the number 1 to puis.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hi, Mebujo! You can improve your code:
for now, you are using two nested loops that means the complexity of the algorithm is O(N^2). However,
you can definitely get the same result with linear complexity.

It would be better, if you define a new function for that, e.g.


def sine_approx(x, degree=5):
    """Sine approximation using Tailor series.
    
    Parameters
    ==========
    
        :param x: some explanation
        :param degree: some explanation
    
    """
    fact = 1
    res = 0
    for i in range(1, degree):
        fact *= i
        if i % 2 != 0:
            res += only one expression is to be written here to complete the function!
    return res
You need to complete sine_approx implementation yourself.
Reply
#4
So i did remove the fact to not complicate it and use the math.factorial, and it did gave me more results, but still with some examples it does not work. the problem is that i dont know the condition that makes me stop. It says the res can not pass 10^(-6).

the new code.

x=float(input())
res=x
import math
sign=1
puis=1
for i in range(3):
    puis=puis+2
    sign=sign*(-1)
    res+=(sign*(x**puis)/math.factorial(puis))
print(res)
Hii scidam, im still new to this code, didnt learn the use of functions yet :c .
Reply
#5
worked with this one
x=float(input())
res=x
import math
from math import sin
sign=1
puis=1
resprec=0
while ((abs(res-resprec))>10**-6):
    puis=puis+2
    sign=sign*(-1)
    resprec=res
    res+=(sign*(x**puis)/math.factorial(puis))
print(res)
Reply
#6
You can find here solutions: https://pythonforundergradengineers.com/...ython.html
Here my example, independently from others.

import matplotlib.pyplot as plt


def sinus(x, degree=21):
    """
   Straight forward implementation.
   """
    sign = -1
    y = 0
    for factor in range(3, degree + 1, 2):
        y += sign * pow(x, factor) / factorial(factor)
        sign *= -1
    return x + y


def cosine(x, degree=21):
    """
   Almost the same like sinus2
   """
    sign = -1
    y = 0
    for factor in range(2, degree + 1, 2):
        y += sign * (pow(x, factor) / factorial(factor))
        sign *= -1
    return  1 + y


def visualize(degree):
    legend = []
    base = [x / 1000 for x in range(-10_000, 10_000, 100)]
    for n in degree:
        legend.append(f'degree={n}')
        plt.plot(base, [sinus(x, n) for x in base])
    legend.append('math.sin(x)')
    plt.plot(base, [sin(x) for x in base])
    plt.legend(legend, loc='upper right', framealpha=0.2, fontsize=8)
    plt.title('Taylor series')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.xlim(-10, 10)
    plt.ylim(-10, 10)
    plt.grid()
    plt.savefig('Taylor series.png', dpi=300)
    plt.show()


if __name__ == '__main__':
    visualize([1, 3, 5, 7, 9, 11, 13])
   

The higher the degree is, the more the range is and the more accurate it is.
Here an example with a degree of 21:
   

Here with dots and a degree of 11:
   

I wish I have to go again to school. :-)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020