Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

3 of 3
replaced http://chat.stackoverflow.com/ with https://chat.stackoverflow.com/

I'm assuming you're using the fourth formula on this page to approximate the log function. If so, your i is starting at the wrong value; you've initialized it to 0 here, but it needs to start at 1.

Also, if you only want output after the answer has been found, rather than once per iteration, your print functions should be de-indented so they are outside the loop. Try:

import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
 print("Your number is not positive. System Shutdown.")
 sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=1
#This is the code to make it go until it hits the error we want
while True:
 ex = 2*i - 1
 lnx += 2.0* (xfrac**ex / ex)
 #Counter adding 1 to it
 i+=1
 #This is the error 
 err = math.fabs(lnx0 - lnx)
 if err<0.0000000001:
 break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)

Result:

Please input a positive number: 5
ln(x) at 5.0 is: 1.6094379123624052
Final error is: 7.169509430582366e-11
Your accurate value of ln(x) is: 1.6094379124341003

Thanks to DSM for identifying the formula and possible fix

Kevin
  • 76.5k
  • 13
  • 141
  • 168

AltStyle によって変換されたページ (->オリジナル) /