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;
}
Related
#include <stdio.h>
#include<math.h>
int series(float,float);
int main()
{
float x,n,series_value;
printf("Enter the value of x: ");
scanf("%f",&x);
printf("\nEnter the value of n: ");
scanf("%f",&n);
series_value=series(x,n);
printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
return 0;
}
int series(float x,float n)
{
int i,sum=0,sign=-1;
int j,fact=1,p=1;
for (i=1; i<=(2*n)-1; i+=2)
{
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
Output:
Enter the value of x: 5
Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1
Why is this message coming? and what is wrong in the program as answer is not coming right
There is a few problems with your code. As #PaulHankin said, when fact overflows and becoms zero, you will have a division by zero, and "weird things" happen.
Your factorial and power calculation is also wrong. You are recalculating it in each iteration of the outer loop without reseting fact and p first:
fact = 1; // You need to reset fact and p to its start value here
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
Your third problem is that for your function calculate the correct value for sin, which is not an integer value, you need to use float, or even better double, when calculating sum. So sum must be declared float, and the division p/fact must use float division. By also declaring p and fact as float, you will solve both the overflow issue, and use the correct division. Naturally your function must also return a float
float series(float x,float n)
{
int i,sign=-1;
int j,
float sum = 0;
float fact = 1;
float p = 1;
for (i=1; i<=(2*n)-1; i+=2)
{
fact = 1;
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
This code still has a minor problem. By having an inner loop, it is slower than necessary. Since this probably is homework, I am not getting rid of that loop for you, just giving you a hint: You don't have to recalculate fact from scratch on each iteration of the outer loop, just try to find out how fact changes from one iteration to the next. The same goes for p.
//Series of Sinx
#include<stdio.h>
#include<math.h>
#define ACCURACY 0.0001
int factorial(int n);
int main()
{
float x,sum,term;
int i,power;
printf("Enter value of X: ");
scanf("%f",&x);
i=1;
power=3;
sum=x;
term=x;
while(term>=ACCURACY)
{
term = pow(x,power) / factorial(power);
if(i%2==1)
{
sum -= term;
}
else
{
sum += term;
}
power+=2;
i++;
}
printf("sin(%f) = %.6f\n",x,sum);
return 0;
}
int factorial(int n){
int i=n,fact=1;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
return fact;
}
plenty bugs. To do not caclulate the fact values all the time they are in the lookup table
#include <stdio.h>
#include <math.h>
double series(double,int);
long long fact[] = { 1, 2, 6, 24,
120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, };
double mypow(double x, unsigned p)
{
double result = x;
while(p && --p)
result *= x;
return result;
}
int main()
{
for(double x = 0; x <= M_PI + M_PI / 60; x += M_PI / 30)
printf("Value of series sin (%.2f) is: %f\n",x,series(x, 5));
fflush(stdout);
}
double series(double x,int n)
{
double sum = x;
int i,sign=1;
for (i=3; i<=(2*n)-1; i+=2)
{
sign=-1*sign;
sum += sign*(mypow(x, i)/fact[i -1]);
}
return (sum);
}
https://godbolt.org/z/U6dULN
maybe its due to floating-point exception as u have declared that the function should return int type value
int series(float,float);//hear
so u can try editing the return type of this function as float
Note:-also u need to change at function definition and the datatype of
int i,sum=0,sign=-1;
int j,fact=1,p=1;
to float as it is returning the value (sum) which should also be float
I've put an printf to check if the function works, but i cant figure out why it doesnt work.
The numbers are all correct in functions, but they dont get executed.
I am not sure why the function isn't working, i dont have much knowledge in C so if anyone could help me that would be much appreciated.
The program is supposed to calculate the odds of you passing the test, by calculating the odds of the people around in your class room.
Example:
P
NXNXNXNXN
ZNZNXXXXX
XNZXNNNZX
ZNXHXXXXZ
NNNNZNNXN
P - professor
Z - prepared student
N - unprepared student
X - an empty seat
H - Me
Input:
3 4
2 50
X X X X
Z H N X
Z N X X
Expected Output:
Sanse za prolaz su 62.50%
Output gotten:
Sanse za prolaz su -0.00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
///FUNKCIJA POSTOTAK
float fudaljenost(int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='Z')
{
Zx=i;
Zy=j;
udaljenostx=abs(Hx-Zx);///A
udaljenosty=abs(Hy-Zy);///B
printf("Z A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak+=90/(udaljenost*udaljenost);///POSTOTAK
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='N')
{
Nx=i;
Ny=j;
udaljenostx=abs(Hx-Nx);///A
udaljenosty=abs(Hy-Ny);///B
printf("N A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak-=30/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
///FUNKCIJA PROFESOR
float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
int Hx,Hy;
int Px,Py;
float udaljenostx=0,udaljenosty=0,udaljenost;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='P')
{
Px=i;
Py=j;
udaljenostx=abs(Hx-Px);///A
udaljenosty=abs(Hy-Py);///B
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak=strogost/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
int main()
{
int i=0,j=0;
int visina,sirina;
int prof;
float strogost;
float posto1,posto2,posto;
char Ucionica[50][50]={0};
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
scanf(" %d%d",&visina,&sirina);
scanf(" %d%f",&prof,&strogost);
///UPIS MATRICE
for(i=1;i<visina+1;i++)
{
for(j=0;j<sirina;j++)
{
scanf(" %c",&Ucionica[i][j]);
}
}
Ucionica[0][prof-1]='P';
posto1 = fudaljenost(visina,sirina,Ucionica);
posto2 = fprofesor(strogost,visina,sirina,Ucionica);
posto = posto1-posto2;
printf("Sanse za prolaz su %.2f",posto);
return 0;
}
Stackoverflow isnt allowing me to post this without adding more words, so im using this part of the text to add more words, sorry stackoverflow for going around the system like this but im kinda running out of time on this.
The current code passed cast on a main variable char Ucionica[50][50]={0} into a function that expects a prototype of float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina]).
From the context, it looks as if the [50],[50[ represent the largest possible input size, but the program will use only the first few rows/columnns (3, 4 in the example). Regardless of how much data will be used, the definition in the called functions should match the data size.
float fprofesor(float strogost,int visina, int sirina,char array[50][50]) { ... }
float fudaljenost(int visina, int sirina,char array[50][50]) { ... }
Side note, gcc -Wall flaggedd many warning on unused variables, but no warning in passing array with mismatch minor array size
Also, probably a good idea to '#define' the maximum size, instead of hardcoding 50 repeated times.
The functions were written wrong,
in
float fudaljenost(int visina, int sirina,char array[visina][sirina])
It wasn't the same size array as sent before[50][50]
The following will fix the problem:
float fudaljenost(int visina, int sirina,char array[50][50])
float fprofesor(float strogost,int visina, int sirina,char array[50][50])
Worth noting that it will be better to #define MAX_ARRAY_SIZE 50, and use MAX_ARRAY_SIZE instead of 50. This will make it easier to avoid error if the number will need to be changed, and will provide hint on what the 50 is.
I have been struggling with this code and just do not seem to grasp what I am doing wrong.
The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!
Here is my code thus far:
#include <stdio.h>
#include <math.h>
float factorial(int n){
if (n==0)
return 1;
else
return 2*n*factorial(n-1);
}
int main (){
float i, n;
float sum=0;
printf("Enter desired interger: ");
scanf("%f", &n);
for (i=0; i<=1; i++)
sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));
printf("The value is %f\n", sum);
return 0;
}
I still working on it, any info or help will be much appreciated!
edit:
Just fixed it guys, this is new format I had to use for my professor:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf(" x mycos(x) cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}
Thank you all for your explanations, they helped out Immensely!
One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.
For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).
another thing I see, is that your denominator is the n! rather than (2 * n)!
For efficiency, I might also implement the factorial routine as follows:
unsigned int factorial(int n){
unsigned int product = 1;
for(int I = 1; I <= n; I++) product *= I;
return product;
}
The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.
float factorial(int n){
float product = 1;
for(int I = 1; I <= n; I++) product *= (float)I;
return product;
}
I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.
Considering computation expense, you need to stop calculating the series at a point. The more you go, the more precise the result will be, but the more your program spends time. How about this simple program:
#include <stdio.h>
#include <math.h>
#define ITERATIONS 10 //control how far you go
float factorial(int n){
if (n==0)
return 1;
else
return n*factorial(n-1);
}
int main (){
float n;
float sum=0;
printf("Enter desired float: ");
scanf("%f", &n);
int c, i;
for (i=0; i<=ITERATIONS; i++) {
c = (i%2)==0? 1 : -1;
sum = sum + (c*pow(n,2*i+1))/(factorial(2*i+1));
}
printf("The value is %f\n", sum);
return 0;
}
1.) You are only multiplying even no.s in factorial function return 2*n*factorial(n-1); will give only even no.s. Instead you can replace n with 2n here- sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(2n)); This will give the correct (2n!).
2.) Check for the no, of iterations for (i=0; i<=1; i++) this will only run your loop twice. Try more no. of iterations for more accurate anwer.
Why are you calculating power etc for each item in the series? Also need to keep numbers in a suitable range for the data types
i.e. for cos
bool neg_sign = false;
float total = 1.0f;
float current = 1.0f;
for (int i = 0; i < length_of_series; ++i) {
neg_sign = !neg_sign;
current = current * (x / ((2 * i) + 1)) * (x / (( 2 * i) + 2));
total += neg_sign ? -current : current;
}
EDIT
Please see http://codepad.org/swDIh8P5
#include<stdio.h>
# define PRECISION 10 /*the number of terms to be processed*/
main()
{
float x,term=1,s=1.0;
int i,a=2;
scanf("%f",&x);
x=x*x;
for(i=1;i<PRECISION;i++)
{
term=-term*x/(a*(a-1));
s+=term;
a+=2;
}
printf("result=%f",s);
}
Your factorial() function actually calculates 2n.n!, which probably isn't what you had in mind. To calculate (2n)!, you need to remove the 2* from the function body and invoke factorial(2*n).
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;
}
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.