I am having an issue with coding infinite sums, here are my professor's instructions & the code I have so far:
This problem is concerned with the area under a normal curve from x = -infinity to a. Write a function to erf(a). The function takes a real parameter, a, and returns a real value. Evaluate the infinite sum by repeatedly computing one term into a running sum until a term is less than 10e-9. To test the function, write a main program that repeatedly reads a real from the terminal & applies erf(a) for that value, until the number is less than -10 (for which the value of erf(a) is essentially 0).
erf(a)= [0.5 + (1 / sqrt(2pi))^(-a / s)] * s(a), where s(a) = the sum of [(a^(2n+1)) / (1,3,5...(2n+1))]
#include <iostream>
#include <cmath>
using namespace std;
double erf(double);
double num = 0.0;
double a, x, n;
int main()
{
do
{
//Get a value
cout << "Enter a value:" << endl;
cin >> n;
//Call erf function
double erf(double a)
{
cout << x << endl;
}
} while (x >= 10e-9);
return 0;
}
//Evaluate erf function
double erf (double a)
{
a = 0.5 + (1/sqrt(2(M_PI)) * (exp(-x(pow(2)) / 2));
x = a * (a/(2n + 1);
num += x;
return num;
}
Your first comment about the library was simply a typo, sorry. To your additional comments, x is supposed to hold s(a) with n being read from the keyboard. Here's my modified code:
#include <iostream>
#include <cmath>
using namespace std;
double erf(double); //prototype
int main()
{
do
{
//Get a value
double a, x, n;
double num = 0.0;
cout << "Enter a value:" << endl;
cin >> n;
//Call erf function
erf(a);
{
cout << num << endl;
}
} while (num >= 10e-9);
return 0;
}
//Evaluate erf function
double erf (double a)
{
a = [0.5 + (1 / (sqrt(2 * M_PI)))] * (exp(-x(pow(2)) / 2));
x = a * (a / (2n + 1));
return num = num + x;
return num;
}
1) The variables a and x are never assigned values in your main(). You are passing a garbage value to erf(), but that's OK because the function doesn't actually use the passed value (should it? If not, why pass it?)
2) The variables x, n and num in your erf() are not the same ones as in the main(). You should be getting errors about these being undeclared identifiers (or not declared in this scope).
If you are getting compiler errors then you should post them in order to aid us in troubleshooting the code.
3) Did you want to do something with the value returned by erf()? You are calling it but not assigning the returned value to anything. I'd cite line #'s in your code but you aren't using the forums code tags. Please use the <> button to the right and place your code in the tags produced.
4) The [] brackets used in erf() are illegal. Another typo?
5) The pow() takes 2 arguments, not 1 (another compile error should result).
If you're trying for e-x^2/2 try calling exp(-x*x/2.0)
Hope that helps you to identify some of the problems.