【发布时间】:2020-04-21 14:09:00
【问题描述】:
我需要在 python 中制作泰勒级数,而不需要导入任何文件,如 import math也不 使用任何内置数学函数,如 round()。
到目前为止,我的余弦函数代码如下:
x = abs(float(input("Please input the degree: ")))
rad = x * 3.14159265358979323846264338327950288419716 / 180
def cos():
f = 1
i = 0
c = 0
T0 = 1
T1 = 0
i = 0
Tp = 1
prec = 11
TDif = 1
print("{0:^45} {1:^13} {2:^47} {3:>12}".format("x", "termOld", "termNew", "tOld - TNew"))
while T1 != T0:
T0 = Tp
T1 = (-1 * T0 * rad * rad) / ((i + 1) * (i + 2))
Tp = T1
f += T1
c += 1
i += 2
TDif = abs(T0) - abs(T1)
print("{:02d} ==> {:^30.11f} {:^30.11f} {:^30.11f} {:^30.11f}".format(c, f, abs(T0), abs(T1), abs(TDif)))
cos()
这是输出:
Please input the degree: 30
x termOld termNew tOld - TNew
01 ==> 0.86292216110 1.00000000000 0.13707783890 0.86292216110
02 ==> 0.86605388342 0.13707783890 0.00313172232 0.13394611658
03 ==> 0.86602526410 0.00313172232 0.00002861932 0.00310310300
04 ==> 0.86602540421 0.00002861932 0.00000014011 0.00002847921
05 ==> 0.86602540378 0.00000014011 0.00000000043 0.00000013968
06 ==> 0.86602540378 0.00000000043 0.00000000000 0.00000000043
07 ==> 0.86602540378 0.00000000000 0.00000000000 0.00000000000
08 ==> 0.86602540378 0.00000000000 0.00000000000 0.00000000000
09 ==> 0.86602540378 0.00000000000 0.00000000000 0.00000000000
...
最后一个重复,直到计数器达到 80。
现在这是我的问题。当termOld (T0) == termNew (T1) 在上面设置的条件下遵循它们设置的精度时,如何停止该功能?就像,如果您查看整个小数点,我知道T0 在计数器 9 上并不是真正的 == T1,但由于精度为 11,我想在只有 0 的字符串时停止它显示为输出,即计数器 07。
【问题讨论】:
标签: python python-3.x function format taylor-series