Approximates the constant e using it's power series A good demonstration of overflow error. Run it yourself!
##include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n;
double approx_e;
double precise_e = 2.7182818284590452353602874713526624977572;
cout << fixed << setprecision(40);
do {
cout << "Enter the number of terms to evaluate after the first or -1 to end: ";
cin >> n;
approx_e = 1.0;
double lastTerm = 1.0;
for (int i=1; i<=n; i++) {
double nextTerm = lastTerm/i;
approx_e += nextTerm;
lastTerm = nextTerm;
}
cout << "\ne is approximately " << approx_e << endl;
cout << "error is " << 100*fabs(precise_e - approx_e)/precise_e << "%\n\n";
} while (n > 0);
}Â
Welford's Algorithm. A good demonstration of overflow error. Run it yourself!
#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>
#include <iomanip>
using namespace std;
double randDouble() {
static int i = 0;
if (i++ < 80)
return (drand48()*100000);
else return 0.0000000000000001;
}
int main()
{
srand48(time(NULL));
array<double, 100> dArr;
double sum = 0.0;
double runningAvg = 0.0;
cout << fixed << setprecision(40);
generate(dArr.begin(), dArr.end(), randDouble);
cout << "Calculating average of array values with 2 different methods ..." <<
endl;
for (auto iter=dArr.begin(); iter != dArr.end(); ++iter) {
int i = iter - dArr.begin() + 1;
sum += *iter;
runningAvg += (*iter - runningAvg)/i;
cout << "After " << i << " numbers:\n";
cout << "\t" << runningAvg << " (running avg. method)\n";
cout << "\t" << sum/i << " (sum method)\n";
cout << "\t\t(sum = " << sum << " , sum method)\n";
}
}