打印结果时强制小数位数

时间:2013-03-02 17:30:07

标签: python printing decimal evaluation

另一种练习。这个要求评估x的值为x-2 = ln(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 work-around的情况下强制执行小数位数?打印resu [i]通常会产生在最接近的十进制“0”(接近代码末尾)之前结束的结果。感谢。

2 个答案:

答案 0 :(得分:1)

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

以下内容适用于您要执行的操作:

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

如果result1.23456sigdig3,则会输出:

x_3 = 1.234

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

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

请注意,除了第17个小数之外的所有内容都是随机垃圾。

答案 1 :(得分:0)

我认为你的问题https://stackoverflow.com/questions/15709496(现已结束)非常有趣。看到它关闭是一件很遗憾的事情,我将继续将其作为练习,并将其发布在以下博客上:http://nickburns2013.wordpress.com/2013/04/01/3d-water-model/。随意评论/添加点点滴滴。

这与这个问题完全无关。向任何关注此主题的人致歉。