Logic help (a trial and error script)
Posted: Mon May 02, 2005 5:04 pm
Hi,
OK my situation is a lot more complex so I'll probably pick a very bad example but it's the logic I can't figure.
Lets say for example I have a function:
Now *imagine* you don't know what the operation is in that function.... all you know is that it outputs a parabola which intercepts the X axis (but we don't know the values).

I want to use trial and error to find what value(s) I input to be within 0.01 of 0.
With me so far?
I need to work out the logic for getting PHP to do the trial and error for me.
I also *know* that these values lies somewhere between -100 and +100 and we also know that going back as far as -100 we are guarunteed to be below the X axis.
I can use two loops if necessary (one that goes forwards and one which goes backwards) to get each point.
I want to avoid writing a whole function to do this. It's going to be part of a single function which *ideally* I dont want to be dependant upon other functions.
The plan was initially to use a for() loop.
Anybody ever done anything like this before?
OK my situation is a lot more complex so I'll probably pick a very bad example but it's the logic I can't figure.
Lets say for example I have a function:
Code: Select all
function parabola($x) {
$y = -1 * $x * $x + 10;
return $y;
}
I want to use trial and error to find what value(s) I input to be within 0.01 of 0.
With me so far?
I need to work out the logic for getting PHP to do the trial and error for me.
I also *know* that these values lies somewhere between -100 and +100 and we also know that going back as far as -100 we are guarunteed to be below the X axis.
I can use two loops if necessary (one that goes forwards and one which goes backwards) to get each point.
I want to avoid writing a whole function to do this. It's going to be part of a single function which *ideally* I dont want to be dependant upon other functions.
The plan was initially to use a for() loop.
Code: Select all
//This should get the first X intercept to within 0.01
$increment = 1;
$i = false;
$intercepted = false;
for ($x=-100; $x<=100; $x+=$increment) {
$y = parabola($x);
if ($i == true) {
$intercepted = true;
}
if (($y/abs($y)) == +1) { //Now above the X axis
$i = true;
$increment *= -1; //Track backwards again
}
if ($intercepted == true) {
if (($y/abs($y)) == +1) { //Above axis
//Do something to the increment to home in on the value
} else {
//Do soemthing else to the increment to home in on the value
}
}
if (abs($y) < 0.01) {
echo $y;
break;
}
}