我正在尝试编写一个程序来计算具有不同精度的pi,并打印出已经过去的数字和时间。我想每次都以当前的准确度打印结果。我使用了print('pi = %*f'%(i, pi))
,其中i
是我当前的浮点精度。这使程序将数字向上舍入为i十进制数字。我正在附上一张图片,显示我的结果运行相同的算法,但改变了输出:
print (" pi = ", pi, " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec")
为:
print (" pi = %.*f"%(i, pi), " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec")
这是我的完整代码:
import time
accuracy = 4
for i in range(1,accuracy + 1):
pi = 0
prevPi = 1
x = 0
t = time.time()
while abs((pi * 4) - prevPi) > 10**((-1)*(i+1)):
#while x < lim:
prevPi = pi * 4
pi += (((-1)**(x))/(1+(2*x)))
#print(abs((pi * 4) - prevPi))
x += 1
pi *= 4
t -= time.time()
print (" pi = %.*f"%(i, pi), " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec")
如何使用i十进制数字打印数字而不进行舍入?
答案 0 :(得分:1)
您可以通过定义截断数字的函数来解决您的问题。该函数可以有两个参数:
number
,position
,会删除以下所有值。def truncate(number, position):
'''Return number with dropped decimal places past specified position.'''
return number - number%(10**position)
例如,如果您希望将数字3.14截断为3.1,则应调用以下内容:
truncate(3.14, -1)
此外,我修改了您的代码,以便更简单并匹配PEP 8 coding conventions。因此,现在它增加了变量命名清晰度和更好的代码格式。
#!/usr/bin/env python3
'''Module for different pi accuracies calculation time comparison.'''
from time import time
def truncate(number, position):
'''Return number with dropped decimal places past specified position.'''
return number - number%(10**position)
def calculate_pi(accuracy):
'''Return pi with certain floating point accuracy.'''
previous_pi = 0
current_pi = 4
iterator = 1
while abs(current_pi - previous_pi) > 10 ** (accuracy-1):
previous_pi = current_pi
current_pi += 4 * ((-1)**iterator) / (1+(2*iterator))
iterator += 1
return truncate(current_pi, accuracy)
def calculation_speed_comparison(max_accuracy):
'''Print comparison of different accuracy pi calculation time.'''
for current_accuracy in range(max_accuracy+1):
calculation_time = time()
current_pi = calculate_pi(-current_accuracy)
calculation_time -= time()
print('pi = {} with {} decimal points accuracy in {} seconds.'.format(
current_pi, current_accuracy, -calculation_time))
calculation_speed_comparison(4)
此代码的输出与原始代码非常相似:
pi = 3.0 with 0 decimal points accuracy in 3.266334533691406e-05 seconds.
pi = 3.1 with 1 decimal points accuracy in 0.00016045570373535156 seconds.
pi = 3.14 with 2 decimal points accuracy in 0.0014882087707519531 seconds.
pi = 3.141 with 3 decimal points accuracy in 0.01430201530456543 seconds.
pi = 3.1415 with 4 decimal points accuracy in 0.1466822624206543 seconds.