2013-03-02 65 views
2

不同的練習。這一個要求評估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解決方法,是否可以強制執行小數?打印結果[i]通常產生的結果在最近的小數「0」之前結束(接近代碼結束)。謝謝。

+0

無論你試圖執行什麼數字:'round(n,sigfig)'。 – 2013-03-02 17:41:31

+0

事情是,我已經編碼它,但它不起作用。它在最接近的小數零之前切割。 – user2126752 2013-03-02 17:45:54

+0

這應該是兩個問題。你在問兩個完全不相關的不同事物。 – 2013-03-02 17:46:19

回答

1

您可以使用*以與C/C++類似的方式在Python格式字符串中使用。當%運算符在格式字符串中遇到*時,它將在列表中查找一個整數並將其用作格式字符串中的常量。

以下應爲工作你正在嘗試做的事:

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

如果result1.23456sigdig3,這將輸出:

x_3 = 1.234 

注意,蟒蛇花車IEEE794 double precision values,這意味着他們有大約15位有效數字。例如:

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

請注意,超出十進制十七進制的所有內容都基本上是隨機垃圾。

+0

我在範圍內(len(resu)): \t print round(resu [i],sigdig) – user2126752 2013-03-02 17:51:32

+0

以上不起作用。如果sigdig = 30,由於某種原因它不會打印30位小數。 – user2126752 2013-03-02 17:52:14

+1

請參閱http://docs.python.org/2/tutorial/floatingpoint.html。 Python浮點數有53位精度,因此要求約15個有效數字是沒有意義的。 – 2013-03-02 17:57:24