简体   繁体   中英

Find maximum value of a function using php

How can I get maximum value of a function in specific range with php. For example I have a function:

function f($x){
    return pow($x,2);
}

and i want to get maximum value of this function in range (-1,1). how can I implement this in php or using some other library?

There's no generic way to do this; you have to do the maths yourself.

Maximisation / Minimisation problems are solved by differentiation. In this case, you would get:

d(x^2)/dx = 2*x

The method for calculating the differential depends on your function. It's not that hard for simple functions like this, and Wolfram Alpha ( http://www.wolframalpha.com/ ) will do it for you if you ask it nicely ( http://www.wolframalpha.com/input/?i=d%28x%5E2%29%2Fdx ).

Then you set that to 0, which tells you when the gradient is 0 (and therefore, it is at a maximum, minimum, or turning point):

2*x = 0

This tells you that you have a point to check at x = 0 (see the "solution" section here: http://www.wolframalpha.com/input/?i=d%28x%5E2%29%2Fdx%3D0 ). Now check the value of your function at the lower bound, upper bound, and the point(s) this tells you to check, and get the maximum/minimum of all those results. This will be your limit within that range.

$maximumValue = -999999999;
for ($i = -1; $i <= 1; $i++) {
    $maximumValue = max($maximumValue, f($i));
}
var_dump($maximumValue);

..should work fine

This will only check for the numbers -1 , 0 and 1 . If you want more precision, just change $i++ to eg. $i += 0.1 :

$maximumValue = -999999999;
for ($i = -1; $i <= 1; $i += 0.1) {
    $maximumValue = max($maximumValue, f($i));
}
var_dump($maximumValue);

This will give you -1 , -0.9 , -0.8 ..... 0.8 , 0.9 and 1 .

It could also be changed to $i += 0.000000001 if you want to waste a lot of resources, but get a more accurate result.

If you use differentiation you have to deal with the case that there are no local optima. If the function is smooth this would mean that the optima occur on the endpoints. I am not sure how precise this all needs to be,but perhaps if the function is just given by a finite list of pairs you could sort a list which contains all the points where the function is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM