別のエクササイズ。これは、x-2=ln(x) について x の値を評価するよう求めました。2 つのアプローチ (A と B) があります。もう 1 つのアプローチは、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] を印刷すると、通常、最も近い 10 進数の「0」の前 (コードの終わり近く) で終わる結果が得られます。ありがとう。