I am learning C# now, so today I was printing the first n-count of number of this progression:
An = 1/n*(-1)^n; So it basically goes -1 1/2 -1/3 1/4... I was wondering if it is better to use if statements if(n%2 == 0)
, or the more elegenat Math.Pow()
method? Is Math.Pow()
slow even for the number 1, when the power is a big int?
Asked
Active
Viewed 133 times
0

Boyan Hristov
- 1,067
- 3
- 15
- 41
-
8Since you're learning programming, how about you build a little program to test it out? Build a big loop (maybe 1 million iterations) and time the results with `System.Diagnostics.Stopwatch` – MikeH Oct 31 '14 at 18:33
-
1You could also consider doing neither, and manually unroll the loop by 2 instead. – harold Oct 31 '14 at 18:34
-
[Does this answers your question](http://stackoverflow.com/questions/8870442/how-is-math-pow-implemented-in-net-framework/8870593#8870593)? – Sriram Sakthivel Oct 31 '14 at 18:34
-
2I wouldn't use Math.pow to alternate a sign. – duffymo Oct 31 '14 at 18:40
2 Answers
1
I'd code it this way using the ternary operator:
double sum = 0.0;
for (int i = 1; i <= n; ++i) {
sum += ((i % 2) == 0) ? +1.0 : -1.0)/i;
}
I like that loop unrolling idea in the comments, too:
double sum = 0.0;
for (int i = 1; i <= n; i += 2) {
sum -= 1.0/i;
}
for (int i = 2; i <= n; i += 2) {
sum += 1.0/i;
}

duffymo
- 305,152
- 44
- 369
- 561
-
1You may want to mention the `ternary` operator in there. Not exactly a beginner idea and it's very hard to search for. – MikeH Oct 31 '14 at 18:43
-
This gets the right idea across, but you are calculating the sum of all An instead of individual An. – Zéychin Oct 31 '14 at 19:57
-
That's true. I'm showing my math bias: I assumed this was a series sum. Note the math tag. – duffymo Oct 31 '14 at 19:58
-
1I know precisely what you mean. Just wanted to clarify so that we don't confuse someone who may have meant one or the other. – Zéychin Oct 31 '14 at 20:01
-
1
Here's another way:
int sign = -1;
for(int n = 1; n <= N; n++)
{
double a_n = (double)sign/n;
sign *= -1;
}

Zéychin
- 4,135
- 2
- 28
- 27