Hi does anyone have an idea how should i apply using loops to compute the following formular in my program? Thanks in advance
x-x^2/2+x^4/4 -x^6/6 + .......... -x^20/20
^ refers to Power of
eg: x^2 is x²
Printable View
Hi does anyone have an idea how should i apply using loops to compute the following formular in my program? Thanks in advance
x-x^2/2+x^4/4 -x^6/6 + .......... -x^20/20
^ refers to Power of
eg: x^2 is x²
hi,
maybe this can give u an idea..
Code:for(double k=2;k<=20;k=k+2)
{
z=Math.pow(x,k)/k;
if(m%2!=0)
{
x=x-z;
m++;
}
else
{
x=x+z;
m++;
}
}
Hi holestary thanks for your quick reply again could you explain to me this part of the code? what am i supposed to declare for m?
Code:if(m%2!=0)
{
x=x-z;
m++;
}
else
{
x=x+z;
m++;
}
it is the same..Code:if(m%2!=0)
x=x-z;
else
x=x+z;
m++;
You change the value of x in every step of the loop, while it should remain constant. A better solution is:
Code:double pow = 1.0;
double sum = x;
double sqr = x * x;
for (double k = 2.0; k <= 20.0; k += 2.0) {
pow = -pow * sqr;
sum += pow / k;
}
Yeah basically i need to compute x- x^3/3 +x^5/5 -x^7/7 +x^9/9 -x^11/11 +x^13/13 -x^15/15 +x^17/17 -x^19/19 which would be = 0.729815 when x=0.9.
I am quite confused with the alternate subtraction and addition of the formular. I guess theres some thing wrong there, that's why i am not getting the correct result?
Code:double z=0, x=0.9,m=1;
for(double k=3;k<=20;k=k+2)
{
z=Math.pow(x,k)/k;
// System.out.println(z);
if(m%2!=0)
{
x=x-z;
m++;
}
else
{
x=x+z;
m++;
}
}
System.out.println(x);
}}
Hugo84, have you seen my post (#6). When you do this:
you are actually changing the value of x, which should remain constant all the time. That is why you are getting the wrong results.Code:x=x+z;
// or
x=x-z;
Now for this new formula with odd exponents the correct code is:
If you run this for x = 0.9 the result (sum) is 0.7298155.Code:double pow = x;
double sum = x;
double sqr = x * x;
for (double k = 3.0; k <= 19.0; k += 2.0) {
pow = -pow * sqr;
sum += pow / k;
}