📄 pex10_8.cpp
字号:
#include <iostream.h>
#pragma hdrstop
// use the bisection method to approximate a root of
// function f that lies between a and b. terminate
// when an exact root is found or (b-a) < precision
double Bisect(double f(double x),
double a,double b, double precision)
{
// m is the midpoint of the interval a <= x <= b
double m = (a+b)/2.0;
// if m is an exact root, return (stopping condition)
if (f(m) == 0.0)
return m;
// if (b-a) < precision, return (stopping condition)
else if (b-a < precision)
return m;
// if the root is in the left half of the interval [a,b],
// call Bisect for a <= x <= m (recursive step)
else if (f(a)*f(m) < 0.0)
return Bisect(f,a,m,precision);
// if the root is in the right half of the interval [a,b],
// call Bisect for m <= x <= b (recursive step)
else
return Bisect(f,m,b,precision);
}
// function f(x) for which roots are desired
double f(double x)
{
return x*x*x - 2.0*x - 3.0;
}
// return the balance after paying simple interest on a given
// principal with monthy interest for nmonths
double Balance(double principal, double interest, int nmonths, double payment)
{
// subtract interest from the payment. use this amount to
// reduce the principal. do this for nmonths
for(int i=1;i <= nmonths;i++)
principal -= payment - principal*interest;
return principal;
}
// use Balance to compute the amount owing on a
// $150000 loan at 10% per year for 25 years. the
// payment is x dollars per month
double SpeficBalance(double x)
{
// interest per month = .10/12,
// number of payments = 25*12
return Balance(150000.0,.10/12.0,25*12,x);
}
void main(void)
{
// approximate the root of f(x) that lies between 1 and 2. use
// precision = 1.0e-8
cout << "Root of x*x*x - 2*x - 3 between 1 and 2 is approximately "
<< Bisect(f,1.0,2.0,1.0e-8) << endl;
// set precision for dollars and cents
cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
// find the root of SpecificBalance between the payments of .01 and 150000
cout << "Payment on the loan is $"
<< Bisect(SpeficBalance,.01,150000.0,1.0e-4) << endl;
}
/*
<Run>
Root of x*x*x - 2*x - 3 between 1 and 2 is approximately 1.893289
Payment on the loan is $1363.05
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -