我需要编写一个代码,首先使用级数展开计算对数的近似,然后显示这个近似,以及近似结果和实际对数结果之间的差异。所有的数字都必须四舍五入到小数点6位。
作为输入,我收到的值是我必须找到对数的数字,以及我想要使用的对数级数展开的多少项。
首先,我必须定义并调用主函数,然后初始化任何变量,然后提示用户输入值,然后设置一个for -循环来执行级数展开,然后计算实际的对数答案,然后计算差额。最后,我必须打印近似值和差值。我还需要确保包括每一步的评论。
实数x (其中0
log(x) = (x-1) - (1/2)(x-1)^2 + (1/3)(x-1)^3 - (1/4)(x-1)^4 +.
我解决的问题是如何使用for循环来交替加法和减法。我也不确定我的其余代码是否编写正确,但它正在运行。不过,我从中得到的答案并不是正确的数学。
下面是我到目前为止编写的代码:
# This program displays the approximate logarithm and the difference between that and the actual logarithm of a number inputted by the user to six decimal places.
# The definition of the main function
def main():
import math
# Initialize any necessary variables and prompt the user for values
num = eval(input("Enter the number whose logarithm you want to be computed: "))
term = eval(input("Enter how many terms of the series expansion for logarithms you want to use: "))
approx = 0
# Setup a loop based on the values entered by the user
# Calculate an approximation to the logarithm of the number entered by the user
for i in range(2, term+1):
if i % 2 == 0:
approx += (num-1) - ((1/i)*(num-1)**i)
else:
approx += (num-1) - ((1/i)*(num-1)**i) + ((1/(i+1))*((num-1)**(i+1))
rapprox = round(approx, 6)
# Compute logarithm and difference
mog = math.log(num)
rmog = round(mog, 6)
diffy = rapprox - rmog
# Display the computed values
print("The computed approximation to log", num, "is: ", rapprox)
print("The difference between the approximation and the actual value for log", num, "is: ", diffy)
# Calling the main function
if __name__ == "__main__":
main()
我们得到了两个样本输出,如下所示:
Please enter the number whose logarithm you want to be computed: 1.5
Please enter how many terms of the series expansion for logarithm you want to use: 5
The computed approximation to log 1.5 is: 0.407292
The difference between the approximation and the actual value for log 1.5 is: 0.001827
这是:
Please enter the number whose logarithm you want to be computed: 0.8
Please enter how many terms of the series expansion for logarithm you want to use: 4
The computed approximation to log 0.8 is: -0.223067
The difference between the approximation and the actual value for log 0.8 is: 0.000077
如果你需要更多的信息,因为这是不清楚的问题,我可以澄清,谢谢!
发布于 2022-01-28 22:04:18
请注意,
log(x) = (x-1) - (1/2)(x-1)^2 + (1/3)(x-1)^3 - (1/4)(x-1)^4 +
= -(1-x) - (1/2)(1-x)^2 - (1/3)(1-x)^3 - (1/4)(1-x)^4 -
= - ( 1-x) + (1/2)(1-x)^2 + (1/3)(1-x)^3 + (1/4)(1-x)^4 +.
因此,可以将对数的近似实现为
def log_approx(x, N):
"""Computes an approximation of log(x) using N terms"""
s = 0.0
for n in range(1, N+1):
s -= (1-x)**n / n
return s或者更短
def log_approx(x, N):
"""Computes an approximation of log(x) using N terms"""
return -sum(((1-x)**n / n for n in range(1, N+1)))https://stackoverflow.com/questions/70900586
复制相似问题