Working on a problem and I am somewhat lost about the mechanics of what needs to be done. I've fleshed it out the best I can but I can tell from my output it's completely off. Instructions are akin to:
given function f(x) = x^3 - 6x^2 - 7x
Write a program that outputs any zero of f(x) (i.e., the value of x for which f(x)=0). Zero is between xleft and xright. Randomly set up values of xleft and xright.
Divide integers xleft and xright in half, compute value of function f(xmid). if positive, xright=xmid.
Halfing of the interval should be done for as long as the value of f(xmid) < AbsoluteCC ie-g.
1.Generate randomly xright
2. Generate randomly xleft so it’s different. Figure out condition.
3. If (xleft > xright), swap.
4. Obtain xmid
5.if f(xmid) has same sign as f(xright) then xright = xmid etc.
Same with xleft
6. Half intervals and calculate xmid as long as |f(x_mid)| < 0
and the code I have so far is:
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
|
#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;
unsigned int seed;
double f (double x);
double random (unsigned int& seed);
double x, x_left, x_right, x_mid;
int main()
{
x_right = rand()*random(seed);
x_left = random(seed);
if (x_left >x_right)
{
x_left = x_left + x_right;
x_right = x_left - x_right;
x_left = x_left - x_right;
}
x_mid = x_left + x_right / 2;
if (f(x_mid) > 0)
x_right = x_mid;
else
x_left = x_mid;
cout << "The zeroes are: ";
cout << endl;
do
{
x_left = x_left/2;
x_right = x_right/2;
cout << f(x_mid);
cout << endl;
} while (f(x_mid) < 0);
return 0;
}
double f (double x)
{
return pow(x,3) - 6 * pow(x,2) - 7*x;
}
double random (unsigned int& seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER * seed) + INCREMENT)%MODULUS;
return double(seed)/double(MODULUS);
}
|
I'm aware this post is sort of a mess so I really appreciate all help.