I am trying to code the summation of the following series:
I can't figure out how to alternate the sign from "-" to " " to "-" and so on....
Here is my code:
#include<stdio.h>
int main()
{
int i=1,n;
float sum,num,den;
den=2;
sum=0;
printf("Enter number of terms for summation: ");
scanf("%d",&n);
for(i=1;i<=n;i )
{
num=i*(i 1);
den=den*(i 2);
sum =num/den;
}
printf("%f",sum);
}
CodePudding user response:
Start a variable at 1.
int coeff = 1;
then:
sum = coeff * num/den;
coeff *= -1; // Toggles -1 to 1 and back to -1 each loop.
When coeff
is 1, then the expression is 1 * -1
, which results in -1
.
When coeff
is -1, then the expression is -1 * -1
, which results in 1
.
the variable keeps toggling back-n-forth between 1
and -1
.
CodePudding user response:
Let’s discuss the methods proposed in comments and other answers in descending order of nominal burden. (By “nominal burden,” I meant what the code literally says to calculate, disregarding potential compiler optimization.)
sum =pow(-1,i)*num/den
. This callspow
, which is a complicated routine. This solution involves a function call and branching through the various special cases thatpow
must handle.if ((i & 1) == 0) num = -num;
. This involves testing, comparing, branching, negating, and assignment. For hardware design reasons, branching may impair performance.int coeff = 1;
,sum = coeff * num/den;
, andcoeff *= -1;
. Okay, now we are on track. We have added just one variable and two multiplications. The latter does not even have to be a multiplication; it could be justcoeff = -coeff;
.
Having learned from those, can we solve it any more simply? Yes, we make a simple change, from:
den=den*(i 2);
to:
den=-den*(i 2);
Then den
will flip between positive and negative each iteration, with just a single negation. However, we do need to start den
with a negative value; den = -2;
.
But then, consider this:
den = den*(-2-i);
Although this involves more characters changed in the source code, it might not be any more work. i 2
may be calculated by taking 2 and adding i
, whereas -2-i
may be calculated by taking −2 and subtracting i
, the same amount of work.
Thus, you can make your program work for alternating signs without any more nominal work than the unchanging sign version.
CodePudding user response:
int main()
{
int i=1,n, sign = 1;
float sum,num,den;
den=2;
sum=0;
printf("Enter number of terms for summation: ");
scanf("%d",&n);
for(i=1;i<=n;i )
{
num=i*(i 1);
den=den*(i 2);
sum =sign * num/den;
sign *= -1;
}
printf("%f",sum);
}
CodePudding user response:
With x = i % 2
alternating between 0 and 1, you have two equations in two variables:
1 = A * 0 B
-1 = A * 1 B
From which you can quickly infer:
B = 1
A = -2
So what you can do is:
const int A = -2;
const int B = 1;
...
for (i = 0; i < n; i )
{
int x = i % 2;
int y = A * x B;
...
sum =y*num/den;
}