I'm trying to code a program that is designed to run an infinite for loop that finds the (x, y) coordinate at which two functions intersect. I've completed writing the program but when running the program, nothing happens.
This is the portion that I think the flaw is:
for (;;) {
// Calculate the y-coordinate's of the Midline.
midLine = (low + high) / 2;
fMid = f(midLine);
gMid = g(midLine);
// if the y-coordinate of fMid == gMid, break and return midLine
if (fMid == gMid) break;
if (fLow < gLow && fHigh > gHigh) {
high = midLine;
fHigh = fMid;
gHigh = gMid;
}
else {
low = midLine;
fLow = fMid;
gLow = gMid;
}
}
I believe the problem lies in my math logic but no matter how I think of it, I can't get my brain to understand where I went wrong. I'd appreciate any tips or hints as to where my logic went faulty.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double solveEq (double(*f)(double x), double(*g)(double x), double low, double high);
double quadratic (double);
double cubic (double);
int main() {
double lo = 0, hi = 0;
printf ("Enter two values for lo and hi: ");
scanf_s ("%lf%lf", &lo, &hi);
double x = solveEq(quadratic, cubic, lo, hi);
printf("\nSuccessful. x = %f.\n", x);
system("Pause");
return 0;
}
double solveEq (double(*f)(double x), double(*g)(double x), double low, double high) {
double fLow = (*f)(low);
double fHigh = (*f)(high);
double gLow = (*g)(low);
double gHigh = (*g)(high);
// check if fLow == gLow intersects or fHigh == gHigh. If they do, break and return X.
if (fLow == gLow) return low;
if (fHigh == gHigh) return high;
double midLine = 0, fMid = 0, gMid = 0;
for (;;) {
// Calculate the y-coordinate's of the Midline.
midLine = (low + high) / 2;
fMid = f(midLine);
gMid = g(midLine);
// if the y-coordinate of fMid == gMid, break and return midLine
if (fMid == gMid) break;
if (fLow < gLow && fHigh > gHigh) {
high = midLine;
fHigh = fMid;
gHigh = gMid;
}
else {
low = midLine;
fLow = fMid;
gLow = gMid;
}
}
return midLine;
}
double quadratic(double x) {
return x*x;
}
double cubic(double x) {
return x*x*x;
}