I am working on the leibniz question as indicated https://www.hackerrank.com/challenges/leibniz here. which computes 1-1/3+1/5-1/7+1/9+... Each element in the sequence can be defined as a(i)=(-1)^i/(2*i+1) start i from 0.
The question requires that to add from the first term to the nth term and output the result. My program passes the basic test cases. But it fails in other cases.
I guess my program fault is due to the precision when the number is large enough.
Can anybody provide a way to improve the precision of the result?
double leibnitz(int n) {
double res = 0.0;
for (int i = 1; i <= n; i++) {
res += 1.0 / (2 * i - 1) * (i % 2 == 1 ? 1.0 : -1.0);
}
return res;
}