Numerical Integration, using the trapezium rule in C - c

I am using the trapezium rule to calculate the integral of a function between 0 and infinity. I can calculate the value of the integral for a given value of N, and now I am trying to loop N from two to a given value but it will not work. It keeps calculating the value of the integral for when N is 2 and repeating instead of the new value of N. The problem is in the for loop in main() I think.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
double f(double x) {
double a;
a =1/((1+x)*pow(x,0.5));
return a;}
double tra(double upper, double lower, int N) {
double sum, step, integral,lowest;
step=(upper-lower)/(N-1);
lower=lower+step;
if(lower==0) {
lowest=DBL_EPSILON;}
else {
lowest=lower;}
while(lower<upper) {
sum=sum+f(lower);
lower=lower+step;}
integral=step*(sum+(f(upper)/2)+(f(lowest)/2));
sum=0;
return integral;}
main() {
int N;
double upper=DBL_EPSILON*2, lower=0, total=0;
for(N=2;N<20000;N+=100) { /*Here im trying to loop N so that the integral is calculated for increasing values of N*/
while(upper<FLT_MAX) {
total=total+tra(upper, lower, N);
lower=upper;
upper=upper*2;}
printf("Integral is %.10f\n", total);
}
}

I suggest you move the variable initialisation to within the for loop like this:
int main(void) {
int N;
double upper, lower, total;
for(N=2;N<20000;N+=100) {
upper = DBL_EPSILON*2;
lower = 0;
total = 0;
while(upper<FLT_MAX) {
total=total+tra(upper, lower, N);
lower=upper;
upper=upper*2;
}
printf("Integral is %.10f\n", total);
}
return 0;
}

Related

can't implement any series that uses power or factorial

I wrote a program to calculate the value of e^x by series and by library function.See the following:
#include<stdio.h>
#include<math.h>
long long fact(int x)
{
long prod=1;
int i=1;
if(x==0)
return 1;
else{
while(i<=x)
{
prod=prod*i;
i++;
}
return prod;
}
}
int main()
{
int i;
float x;
double sum=1;
for(x=1;x<20;x++)
{
for(i=1;i<=10;i++)
{
if(fact(i)!=0);
sum=sum+pow(x,i)/fact(i);
}
printf("by code e=%.15lf\t\t",sum);
printf("by libfnc e=%.15f\t",exp(x));
printf("quotient =%.15f\n",sum/exp(x));
}
}
The code works for smaller values like 1,2 but with the increase of the value of x the difference (here quotient) increases.That is my code no longer gives correct answer for higher values of x.
You need function prototype before calling it.
Add some ifs to check if you do not divide by zero.
scanf returns number of successfully scanned elements. Check for 1 in this case.
int fct = fact(2*i);
if(fct)
sum=sum+y/(double)fct;
else
{printf("DIVISION BY ZERO!!!!\n"); return 1;}
You will discover that int is to small for factorial function. Change it to double. Also, use double in all floating point operations.
double fact(int x);
int main()
{
double sum,y;
int x,i=0;
double fct;
while(scanf("%d",&x) == 1)
{ sum=0;
for(i=0;i<=N;i++)
{
y=pow(-1,i)*pow(x,2*i);
fct = fact(2*i);
if(fct != 0.0)
sum=sum+y/fct;
else
{printf("DIVISION BY ZERO!!!!\n"); return 1;}
}
printf("using Maclaurin's series %.10f and original cosx=%.10f",sum,cos(x));
}
}
double fact(int x)
{
double prod=1.0;
int i=1;
for(i=1;i<=x;i++)
prod=prod*i;
return prod;
}
https://godbolt.org/z/qsh4qh3d1

Determination of polynomials

I need help solving this task, if anyone had a similar problem it would help me a lot.
The task is:
Write a program that calculates the degree and polynomial p(x) for a given x.
For example:
Enter n:2 //degree of polynomial and function degree
Enter x:2
x^n=4
Enter coefficients of polynomial:
a[0]=1
a[1]=2
a[2]=3
P(x)=3*x^2 + 2*x^1 +1*x^0 = 17
I did it like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
/*
*/
typedef struct polynomial {
double coef[MAX];
} POLYNOMIAL;
double degree(double ,int );
double px(POLYNOMIAL ,double );
int main()
{
POLYNOMIAL p;
double x,pom;
int n;
printf("Enter degree (n>=0):");
scanf("%d",&n);
while(n<1 || n>MAX)
{
printf("Enter degree (n>=0):");
scanf("%d",&n);
}
printf("Enter x:");
scanf("%lf",&x);
pom=degree(x,n);
printf("%.2lf^%d =%lf",x,n,pom);
printf("\nEnter coefficients of polynomial :\n");
for(int i=0;i<=n;i++)
{
printf("a[%d]:",i);
scanf("%lf",&p.coef[i]);
}
return 0;
}
double degree(double x,int n)
{
double degree=1;
if(n==0)
{
return 1;
}
for(int i=1;i<=n;i++)
{
degree*=x;
}
return degree;
}
double px(POLYNOMIAL p,double x)
{
double sum=0;
for(int j=0;j<"I don't know what to put here";j++)
{
sum+=(double)p.coef[j]*degree(x,j);
}
printf("%lf",sum);
}
The problem arises when calculating polynomials, because I don't know what to put as a condition in the for loop, there should be j < of the length of the array entered, that is, of degree n,
but n cannot be used as a parameter in the px function? The task must be done with the structure and functions listed.
Thanks in advance !
If you are not allowed to pass n to the function, you can instead just loop to MAX and make sure that all unused coefficients are zero.
In other words, just initialize all elements of p to zero
POLYNOMIAL p = {.coef = {0} };
and let the loop be:
j < MAX
BTW: Notice that you need return sum in the function.
Further the function degree is pretty unnecessary. Consider this:
double px(POLYNOMIAL p,double x)
{
double sum=p.coef[0];
double d = x;
for(int j=1;j<MAX;j++)
{
sum+=(double)p.coef[j]*d;
d = d * x;
}
printf("%lf",sum);
return sum;
}

SUM Recursive function in C

I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs.
I have this and i think it should work but i'm not entirely sure why its not
#include <stdio.h>
int main()
{
int sum (x, max);
int total, y, x, max;
if (x<max){
y=x+1;
total = x+sum(y,max);
return total;
return x;
}
return 0;
}
Thanks for any help with this in advance!
Here is one possible solution:
#include <stdio.h>
int sum_in_range(int a, int b){
if(a != b){
return sum_in_range(a+1,b)+a;
}
else{
return b;
}
}
int main(void) {
// your code goes here
printf("%d",sum_in_range(2,4));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int sum(int s,int max)
{
if(s==max)
{
return s;
}
else
{
return(s+sum(s+1,max));
}
}
int main()
{
int r,s,max;
printf("\n enter s and max");
scanf("%d%d",&s,&max);
r=sum(s,max);
printf("%d",r);
}
I spotted some errors on your code. I'm not a pro yet but here's what I think
I just edit your code. removed, added and rearranged some stuff*/
/*First, let's look at your code*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum(x, max);//I think what you want to do here is declare a function but instead declaring, you define it here because you added semicolon (;)
int total, x, y, max;
if(x < max)
{
y = x + 1;
total = x + sum(y, max); //you don't have a function declaration for "sum"
return total;
return x; //this will never return since you already "return the total before this"
}
return 0;
}
//////////////////////////////////////////////////////////////
/*And I think this is what you want to do*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6; //We declare this here for the "sum" function. This way "sum" function can recognize these variables
int total = x; //be sure to set the total to x.
//you can make a void function for this instead of "int". but either way, it can do the job.
void sum(int y) //no need to pass a "max" because "max" is already recognized by the "sum" function since we declare the variables at the top of "main" function
{
if(x < max)//don't make it x <= max. Because of the argument "total = total + (x + 1)" on this function. If you do, the total will exceed.
{
//You can see here why we set the value of "total" to x.
total = total + (x + 1);//And also, you can see why we didn't make the argument in if() statement like this: if(x <= max).
x++;//increment "x" every loop
//call the function again and pass the total until x == max.
sum(total);
}
}
//pass the x
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
//////////////////////////////////////////////////////////////
/*It looks messy with comments*/
/*Here's the code looks like without a comment.It's pretty short code if you look remove the comments.. LOL..*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6;
int total = x;
void sum(int y)
{
if(x < max)
{
total = total + (x + 1);
x++;
sum(total);
}
}
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}

Help needed with making a program that calculates moving average

I need to calculate average with the size of span and which is moving by one element and outputting the average of elements till the end.
#include <stdio.h>
#include <stdlib.h>
void moving_average (int size, double a[], int span)
{
int k;
double sum;
int n;
int count;
double output;
n=size-span;
for(count=0;count <= n;count++)
{
for(k=count; k<(count+span); k++)
sum+=a[k];
output=sum/span;
printf("%lf", output);
}
}
int main(void)
{
double array[]={10,9,15,6,7};
moving_average(5,array[], 2);
return 0;
}
Increase the warning level of your compiler!
There's a syntax error in the call to moving_average() which your compiler should have caught.
And sum is not initialized which your compiler should warn you about if it is properly setup.
Remove the brackets after array in the call to moving_average
Set sum = 0 before for(k=count; k<(count+span); k++)
add a \n in your printf

Help implementing Least Squares algorithm in C [was: want to find the square root of an array]

the formula is pretty complicated. the numerator is num and the denominator is den, in the formula there is a root on the denominator so i have putted den in sqrrt() but sqrrt only accepts doubles
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define LEN 11
// for the following set of x and y find r by the formula ..
float sum(float arr[]);
void main(void)
{ int i;
float x[]={43.22,39.87,41.85,43.23,40.06,53.29,53.29,54.14,49.12,40.71,55.15};
float y[]={102.43,100.93,97.43,97.81,98.32,98.32,100.07,97.08,91.59,94.85,94.6};
float num,den[LEN],r[LEN],xy[LEN],x2[LEN],y2[LEN];
for(i=0;i<LEN;i++)
{
x2[i]=x[i]*x[i];
y2[i]=y[i]*y[i];
xy[i]=x[i]*y[i];
}
num=sum(xy)-sum(x)*sum(y);
for(i=0;i<LEN;i++)
{
den[i]=((LEN*sum(x2)-(sum(x))*(sum(x)))*(LEN*sum(y2))-(sum(y2))*(sum(y2)));
r[i]=num /sqrt(den); /*<----------the problem is here-----> */
}
printf("%f",r);
getch();
}
float sum(float arr[])
{
int i;
float total=0;
for(i=0;i<=LEN;i++)
{
total+=arr[i];
}
return total;
}
Out of sheer boredom I have fixed your code. It is still ugly and extremely inefficient but compiles and should work. I'll leave you or someone else to make it decent.
#include <stdio.h>
#include <math.h>
#define LEN 11
// for the following set of x and y find r by the formula ..
float sum(float arr[]);
int main(void)
{ int i;
float x[]={43.22,39.87,41.85,43.23,40.06,53.29,53.29,54.14,49.12,40.71,55.15};
float y[]={102.43,100.93,97.43,97.81,98.32,98.32,100.07,97.08,91.59,94.85,94.6};
float num,den,r[LEN],xy[LEN],x2[LEN],y2[LEN];
for(i=0;i<LEN;i++)
{
x2[i]=x[i]*x[i];
y2[i]=y[i]*y[i];
xy[i]=x[i]*y[i];
}
num=LEN*sum(xy)-sum(x)*sum(y);
den = (LEN*sum(x2)) - sum(x)*sum(x);
float alpha = sum(y)/LEN - (num/den)*sum(x)/LEN;
printf("beta = %f, alpha = %f\n", num/den, alpha);
for(i=0;i<LEN;i++)
{
float term = y[i] - alpha - (num/den)*x[i];
r[i] = (term*term);
printf("%f",r[i]);
}
}
float sum(float arr[])
{
int i;
float total=0;
for(i=0;i<=LEN;i++)
{
total+=arr[i];
}
return total;
}
To be consistent with the rest of the code, you should presumably be writing:
r[i] = num / sqrt(den[i]);
However, the calculation is not one I recognize. The body of the second loop is going to produce the same result for each value in den and therefore also in r, which is probably not what the question asked for.
You need to give the index den[i] at the denominator....instead in your code you have just passed the base address!
r[i]=num /sqrt(den[i]);
If this is what you want to achieve, which is quite unclear.

Resources