1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#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;
}
|