Python Forum
While loop - series expansion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: While loop - series expansion (/thread-23236.html)



While loop - series expansion - StillAnotherDave - Dec-17-2019

Hello folks,

I've put together the following code for a series expansion for the function ln(1+x):

import numpy as np


x = float(input('Please input a number x between 0 and 1 '))
logx = np.log(x+1)
while x<=0 or x>=1:
    float(input('Please input a number between 0 and 1 '))
    
for n in range(1, 13):
    term1 = x
    term = ((-1)**(n+1))*(x**n)/n
    term1 += term
print('The sum of the Taylor expansion for ln(1+x) upto x^12 is: ', term1)
I'm stuck on the following task:

calculate and print out the value of ln(1 + x) calculated using the above series expansion using a while loop and including all terms whose magnitude are bigger than 10−8. Print out the sum to each number of terms.

Can anyone help explain how to do this?


RE: While loop - series expansion - StillAnotherDave - Dec-18-2019

Any help??


RE: While loop - series expansion - ibreeden - Dec-18-2019

It is not clear to me what you want. Not everybody is aquainted to "Taylor expansion". Perhaps you could explain a bit. (This may help you because one can never make a program of something one does not understand thorougly.)
And you already have a program. Does it not do what you want? Does it result in error messages? Or is the only goal to change the "for-loop" into a "while-loop"?


RE: While loop - series expansion - scidam - Dec-19-2019

Suppose you've correctly defined Taylor series; Taylor series is a sum, but you don't calculate the sum:
you are resetting term1 in the loop. Moreover, term1 is not an appropriate name for the sum. It is very important
to assign right names to variables. Appropriate name would be, at least, partial Taylor sum/series (partial_sum), truncated Taylor series (truncated_sum) etc.

taylor_sum = 0
for n in range(1, 13):
    term = ((-1)**(n+1))*(x**n)/n
    taylor_sum += term

# taylor_sum is the result you want