2013-04-02 40 views
0

在这个post的Jamie帮助下,我知道我需要使用scipy.optimize。不过,我不断收到以下错误:在scipy中优化iPython错误

Traceback (most recent call last): 
    File "./hw7problem5.py", line 19, in <module> 
    print(max_R) 
NameError: name 'max_R' is not defined 


#!/usr/bin/env python 
# Plotting the energy for circular Hohmann transfer 

import scipy 
import matplotlib 
import numpy as np 
import pylab 


def f(R): 
    return ((1/np.sqrt(R)) - ((np.sqrt(2) * (1 - R))/(np.sqrt(2) 
     * (1 + R))) - 1) 
    max_r = scipy.optimize.fmin(lambda r: 1/f(r), 20) 

x = np.arange(1, 25, 0.001) 
pylab.plot(x, f(x), 'r') 
pylab.show() 

print(max_R) 

回答

0

这似乎是由于工作和输出正确的解决方案。

#!/usr/bin/env python 
# Plotting the energy for circular Hohmann transfer 

import scipy 
import matplotlib 
import numpy as np 
import pylab 
from scipy.optimize import fmin 


def f(R): 
    return ((1/np.sqrt(R)) - ((np.sqrt(2) * (1 - R))/(np.sqrt(R 
     * (1 + R)))) - 1) 

x = np.arange(1, 20, .001) 
max_r = fmin(lambda r: 1.0/f(r), 20) 

pylab.plot(x, f(x), 'r') 
pylab.show() 

print(max_r) 
1

max_R应该max_r。 Python区分大小写。

您还没有保存您的函数的结果的任何地方:

x = np.arange(1, 25, 0.001) 
max_r = f(x) 

pylab.plot(x, max_r, 'r') 
pylab.show() 

print(max_r) 
+0

我的输出窗口只显示:[0.00000000e + 00 1.24812711e-07 4.98503368e-07 ...,1.23080047e-01 1.23079006e-01 1.23077965e-01] 反正我有扩大输出显示? – dustin

+0

@dustin:你必须用'for'循环遍历它们并单独打印每一个。 – Blender

+0

那么反正只是为了返回一个单一的r值,而不是一个数组? – dustin