gpt4 book ai didi

python - 在Python中动态改变浮点精度

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:32 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,以不同的精度计算 pi 并打印出数字和耗时。我想每次都以当前的精度打印结果。我使用了 print('pi = %*f'%(i, pi)) ,其中 i 是我当前的浮点精度。这使得程序将数字四舍五入到小数点后第 i 位。我附上一张图片,显示运行相同算法但改变输出的结果:

print("pi=",pi,"=with",i-1,"小数点精度=in:",(-1)*t,"sec")

至:

print("pi = %.*f"%(i, pi),"=with",i-1,"小数点精度= 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")

enter image description here

如何打印 i 位十进制数字而不进行四舍五入的数字?

最佳答案

您可以通过定义截断数字的函数来解决您的问题。该函数可以接受两个参数:

  1. number 您想要截断的数字,
  2. 位置,在该位置它将删除所有后续值。
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.

关于python - 在Python中动态改变浮点精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com