maximum of a function on a specified domain in iPython

╄→尐↘猪︶ㄣ 提交于 2019-12-24 16:57:02

问题


I am trying to find the maximum of the following function for 1 < R < 20. How can I implement this into the code?

The solution is supposed to be R is approx 15.5 or so.

#!/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

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

回答1:


You can use scipy.optimizie.fmin:

>>> scipy.optimize.fmin(lambda r: -f(r), 10)
Optimization terminated successfully.
         Current function value: -0.134884
         Iterations: 16
         Function evaluations: 32
array([ 11.44451904])

Which is where the maximum actually is:

>>> x = np.linspace(1, 20, 1000)
>>> plt.plot(x, f(x))
[<matplotlib.lines.Line2D object at 0x0000000007BAEF98>]
>>> plt.show()



来源:https://stackoverflow.com/questions/15754637/maximum-of-a-function-on-a-specified-domain-in-ipython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!