// For: https://forum.arduino.cc/t/basic-mathematical-equationcoding/1073852
// "Find" x by searching for it.
float bottom_x;
float bottom_y;
void setup()
{
Serial.begin(115200);
Serial.setTimeout(100); // 100 ms timeout for serial input
// Find the bottom between -1000 and +1000 with step 1.0
bottom_x = -1000.0;
bottom_y = Calc(bottom_x);
for( float x=-1000.0; x<1000.0; x+=1.0)
{
float y = Calc(x);
if( y < bottom_y)
{
bottom_y = y;
bottom_x = x;
}
}
// Find a more accurate bottom with step 0.001
for( float x=bottom_x-1.0; x<bottom_x+1.0; x+=0.0001)
{
float y = Calc(x);
if( y < bottom_y) // new lower bottom ?
{
bottom_y = y;
bottom_x = x;
}
}
Serial.print( "The bottom of the curve is at x=");
Serial.print(bottom_x);
Serial.print(" (y=");
Serial.print(bottom_y);
Serial.println(")");
Serial.println("Enter a value for y (integer value)");
}
void loop()
{
if( Serial.available() > 0)
{
// using parseInt, even though I don't like that function
long y_int = Serial.parseInt();
while( Serial.available() > 0)
Serial.read(); // remove trailing CR or LF
float y_target = float( y_int);
if( y_target < bottom_y)
{
Serial.println("That value is not in the curve");
Serial.println("Enter a good value for y (integer value)");
}
else
{
// search upward
Serial.print("Searching upward ...");
delay(1000);
Serial.println("... not implemented yet");
// search downward
Serial.print("Searching downward ...");
delay(1000);
Serial.println("... not implemented yet");
Serial.println("Enter a new value for y (integer value)");
}
}
}
float Calc( float x)
{
float y = (0.0227*x*x) - (3.1401 * x) + 177.35;
return( y);
}