因此,此代码旨在返回最终错误和用户输入的数字的最终对数。现在我的问题是它没有运行循环,它只是继续经过相同的数字,它永远不会结束。我不确定我的错误区域是否有我的打印语句,或者我是否在循环错误但我希望循环在错误小于1x10 ^ -9时结束。我的迭代也可能设置错误,不能确定我在这里搞砸了什么。
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=0
#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)
答案 0 :(得分:3)
我假设您正在使用this页面上的第四个公式来近似日志功能。如果是这样,您的i
开头的错误值;你在这里将它初始化为0,但它需要从1开始。
此外,如果您只想在找到答案后输出,而不是每次迭代一次,那么您的print
函数应该被缩进,以便它们在循环之外。尝试:
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)
结果:
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
感谢DSM确定公式和可能的修复
答案 1 :(得分:1)
这有几个问题。首先是你的计算不正确。我试着进入&#39; e&#39;到9个地方。你的估计,lnx,迅速退化到-3.3279+并坚持到那里。这会使你陷入无限循环,因为估计永远不会接近真实值。
其他人已经指出你没有用print语句跟踪你的计算。我将在数值分析中添加另一个提示:使用受限制的&#34;用于&#34;循环直到你调试了计算。 然后将其换成&#34;而错误&gt;公差&#34;循环。
要解决您最近的评论,您不获取相同的数字。前几个术语很重要,但是无限序列很快就会接近0,所以在大约15-20次迭代后,这些加法不会出现。
还在循环中打印出ex和lnx值。特别检查第一个,你的指数是-1;我相信你已经在错误的地方开始了循环。
最后,您可能会发现此循环形式更容易阅读。摆脱你的if ... break语句并改为使用它:
i = 1
err = 1
tolerance = 1e-10
# This is the code to make it go until it hits the error we want
while err >= tolerance: