So I've been trying to implement a small program to calculate double integral using simpsons 1/3 rule for a college assignment using the obsolete turbo c++ compiler (yes, we still use it!) but sadly I've seem hit a strangle glitch. Whenever I try add elements of array ax[i] in following program that gives me a zero. The elements seem to be showing up perfectly in and of themselves but adding them results in a zero for some strange reason. Here's the piece of code.
#include<iostream.h>
#include<conio.h>
#include<math.h>
double f(double, double);
void main()
{
clrscr();
double a, b, c, d, h, k, ans, z[10][10], ax[10];
int i, j, nx, ny;
clrscr();
a=0.0; b=1.0; c=0.0; d=1.8; h=0.25; k=0.30;
nx = (b-a)/h;
ny = (d-c)/k;
for(i=0; i<10; i++)
{
for(j=0; j<10;j++)
z[i][j] = 0;
ax[i] = 0;
}
//Generating the table
for(i=0; i<=nx; i++)
{
for(j=0; j<=ny; j++)
{
z[i][j] = f(a+i*h, c+j*k);
}
}
for(i=0; i<=nx; i++)
{
ax[i] = 0.0;
for(j=0; j<=ny; j++)
{
if(j==0 || j==ny)
ax[i] += z[i][j];
else if(j%2==1)
ax[i] += 4*z[i][j];
else
ax[i] += 2*z[i][j];
}
ax[i] *= k/3.0;
cout<<ax[i]<<endl;
}
ans= 1.0;
//for(int q=0; q<=nx; q++)
ans= (ax[0])+(ax[1])+(ax[2]);
cout<<"Value of integral is: "<<ans;
getch();
}
double f(double x, double y)
{
float r;
r = 2*x*y/sqrt(x*x+y*y);
return r;
}
Ideas?
double f(double x, double y)
{
float r;
r = 2 * x*y / sqrt(x*x + y*y);
return r;
}
Divides by zero when x=0
and y=0
, so ax[0]
equals nan
. When you add the numbers up, you're going to get nan
as the output. You need to use L'Hopital's rule to evaluate that limit, and handle the first element differently.