Skip to main content
 首页 » 编程设计

python之打印结果时强制小数位数

2025年05月04日9artech

不同的练习。这个要求计算 x-2=ln(x) 的 x 值。有两种方法(A 和 B)- 一种使用给定的方程式并产生较小的解 (x1)。另一种方法使用 e**(x-2)=x 并产生另一个解 (x2)。

程序绘制图形解,然后查询初始值输入。然后它使用适当的方法评估 x。方法 A 要求初始条件小于 x2,方法 B 要求初始条件大于 x1。这两种方法都适用于介于 x1 和 x2 之间的初始条件。

代码的最后一部分操纵输出以仅打印唯一的解决方案。

# imports necessary modules 
 
import matplotlib.pyplot as plt 
import numpy as np 
 
# plots the equation to provide insight into possible solutions 
 
p = [] 
x = np.arange(0,5,0.01) 
f = x - 2 
g = np.log(x) 
 
plt.plot(x,f) 
plt.plot(x,g) 
 
plt.show() 
 
# x - 2 = ln(x) 
 
print 
lista = map(float, raw_input("Provide the starting conditions to establish the approximate value of the solutions to x-2=ln(x) (separate with spacebar): ").split(" ")) 
print 
sigdig = int(raw_input("Define the number of significant digits (up to 15): ")) 
print 
 
results1 = [] 
results2 = [] 
results3 = [] 
results4 = [] 
 
results = [] 
resu = [] 
 
for i in lista: 
 
    if i > 0.1586: 
        y = i 
 
        left = y - 2 
        right = np.log(y) 
        expo = "%d" % sigdig 
        epsi = 10**(-int(expo)-1) 
        step = 0 
 
        while abs(left - right) > epsi: 
            y = right + 2 
            right = np.log(y) 
            left = y - 2 
            step += 1 
            results1.append(y) 
        results2.append(results1[-1]) 
 
    if i < 3.1462: 
        z = i 
 
        left = np.e ** (z - 2) 
        right = z 
        expo = "%d" % sigdig 
        epsi = 10**(-int(expo)-1) 
        step = 0 
 
        while abs(left - right) > epsi: 
            z = np.e ** (right - 2) 
            left = np.e ** (z - 2) 
            right = z 
            step += 1            
            results3.append(z) 
        results4.append(results3[-1]) 
 
# combines and evaluates the results 
 
results = results2 + results4 
 
for i in range(len(results)): 
    if round(results[i], sigdig) not in resu: 
        resu.append(round(results[i], sigdig)) 
    else: 
        pass 
 
print "For given starting conditions following solutions were found:" 
print 
 
for i in range(len(resu)): 
    printer = '"x_%d = %.' + str(sigdig) + 'f" % (i+1, resu[i])' 
    print eval(printer) 

我的问题是:是否可以从图形解决方案中输入 x1 和 x2 的近似值(第 36 和 53 行)而不是对它们进行硬编码?如果代码中没有 eval 解决方法,是否可以强制执行小数位数?打印 resu[i] 通常会产生在最接近的小数点“0”(接近代码末尾)之前结束的结果。谢谢。

请您参考如下方法:

您可以使用与 C/C++ 类似的方式在 python 格式字符串中使用 *。当 % 运算符在格式字符串中遇到 * 时,它会在列表中查找整数并将其用作格式字符串中的常量。

以下应该适用于您正在尝试做的事情:

print "x_%d = %.*f" % (sigdig,sigdig,resu[i]) 

如果result是1.23456并且sigdig是3,这将输出:

x_3 = 1.234 

注意 python float 是 IEEE794 double precision values ,这意味着它们有大约 15 位有效数字。例如:

>>> print "x_%d = %.*f" % (30,30,1.0/3.0) 
x_30 = 0.333333333333333314829616256247 

请注意,小数点后 17 位之后的所有内容本质上都是随机垃圾。