# Simpson 3/8 rule

This is a discussion on Simpson 3/8 rule within the C Programming forums, part of the General Programming Boards category; Hi all I just finished my simpson 3/8 rule program. But I'd like to modify it. The program should stop ...

1. ## Simpson 3/8 rule

Hi all

I just finished my simpson 3/8 rule program. But I'd like to modify it.
The program should stop when a given precision is reached...Without the
if clause the programm calculates the value very good..but how can I maked it stop, when the precision of 10^6 is reached?

Code:
```#include <stdio.h>
#include <math.h>

double function(double x);

main()
{
printf("-----The Program calculates the integral with 'Simpson 3/8 rule'-----\n");

// Interval: [a,b] h=(b-a)/3m
// e.g choose m = 100 so I have 300 strips
int m = 50000;
int a = -1;
int b =  1;

double h = (double)(b-a)/(3*m);
double funArray[3*m];
int funArraySize = sizeof(funArray)/sizeof(double);

// funArray index
int i = 0;
// function values
double k;
for(k=-1;k<=1;k=k+h)
{
funArray[i] = function(k);
i++;
}
double tmp;
int r;
double simpsonSum = 0;
for(r=1;r<=m;r++)
{

simpsonSum = simpsonSum + funArray[3*r-3]+3*funArray[3*r-2]+3*funArray[3*r-1] + funArray[3*r];
// if clause which does not work ..
if(h*(0.375)*abs(tmp-simpsonSum)<0.000001)
break;
tmp = simpsonSum;
}
simpsonSum = (double)simpsonSum*h*(0.375);
printf("%0.10lf", simpsonSum);

return 0;
}

double function(double x)
{
return (log(1+pow(x,2))*sqrt(cos(x)));
}```
thx for helping me!

Matts

2. You should know this code will only work on C-99 compliant compilers. This is because of the way you are declaring variables and arrays on the fly.

Do you want 10^6 or 10^-6?

Also are you really sure you want to be creating an array of 150,000 doubles (~1 mB) on your program's stack? (This is a good time to learn about malloc() and free()...)

Finally when you use a for loop such as for (r = 1; r <= m; r++) you run a very real risk of running off the end of your array... like in calculations such as funarray[3*r-1].... In C array indeces start at 0, not 1... thus an array of 5 elements has useable indexes from 0 to 4... you need to respect this when writing code as an array bounds overrun can and does crash programs. You should start your loop at 0, exit at r < m and adjust the offsets in your index calculations.

3. I don't know why you think you can stop an integral early, because you can't. You'll stop whenever your function values get small, but that's no guarantee that they don't get big again later.

4. Yes, this isn't a (typical) series in which the terms get smaller and smaller.