Pregunta

I'm trying to program Composite Simpson's Rule in C. The formula is:

enter image description here

where x_j=a+jh for j=0, 1, ..., n-1, n with h=(b-a)/n; in particular, x_0=a and x_n=b.

For some reason, the first and second loop have the same value. I checked over this a lot of times, but I can't seem to find my mistake.

#include <stdio.h>
#include <math.h>

float f(float);
float a;
float b;
float x;
float h;
int n;
int j;


 a=0;
 b=2;
 n=8;
 h = (n - j) / b; 

float first;
float second;
int main() {


  sum = (h / 3.0f) * (f(h) + f(n));

  printf("%f\n", sum);

  second =  (4.0f) * h * f(a);
  }
  printf("second sum: %f\n",second );

  sum = sum + first + second;
  printf("%f\n", sum); 
  return 0;
}

The answer should be around 3.1 (The value of the final sum)

¿Fue útil?

Solución

Your divisions won't probably do what you expect:

(2 / 3) == 0

Dividing int with int will result in int.

Use float constants (2.0f / 3.0f)

Edit:

You still have the same problem with the other n / 2.

And you should use %f when printing floats: printf("first sum: %f\n",first);

The value of the integral is: 3.109337

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top