[英]Find x where y is minimum
I have a polynomial in a range (-2,2) .我有一个(-2,2) 范围内的多项式。 I can easily find min y values by iterating with x=0.1 .我可以通过迭代x=0.1轻松找到 min y 值。 But I also want to find corresponding x value where y is minimum.但我也想找到对应的 x 值,其中 y 最小。 (without using any additional libraries) (不使用任何额外的库)
Let's say y=x**2+3*x+5.假设 y=x**2+3*x+5。 I want to find min(y) in a range(-2,2) and also want to find x which gives min(y).我想在范围(-2,2)中找到 min(y),并且还想找到给出 min(y)的 x。
def f(x):
return x**2+3*x+5
y=[]
x=[i/10 for i in range(-20,20)]
for x in x:
y_values.append(f1(x))
#min(y) find also minimum of y but I want to find it with long way.
minimum1=y_values[0]
for n in y_values:
if minimum1>n:
minimum1=n
Since tuples are ordered by the first items and then the second items and so on, you can pass to the min
function a generator expression that outputs tuples of (y, x)
:由于元组按第一项排序,然后是第二项,依此类推,您可以将输出(y, x)
元组的生成器表达式传递给min
function:
min((f(x), x) for x in (i / 10 for i in range(-20, 20)))
This returns:这将返回:
(2.75, -1.5)
Maybe just doing the comparison at the same time you call the function?也许只是在您调用 function 的同时进行比较?
def f(x):
return x**2+3*x+5
y=[]
x=[i/10 for i in range(-20,20)]
ymin = f1(x[0])
xmin = x[0]
for x in x:
if(f1(x)<y):
ymin = f1(x)
xmin = x
y_values.append(f1(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.