How to write 1+1/2+1/3....+1/4999+1/5000 in java?
How to write 1+1/2+1/3....+1/4999+1/5000 in java? I have tried this but didnt work.
public class Harmonic{
public static void main(String[] args){
double sum 开发者_如何学C= 0;
for(int i=1; i<=5000; i++){
sum+=1/i;
}
System.out.println(sum);
}
}
Adding numbers from smallest to largest will have a lower rounding error. If you compare the result with higher precision, you can see smaller to larger is closer.
double sum = 0;
for (int i = 1; i <= 5000; i++) {
sum += 1.0 / i;
}
System.out.println("From largest to smallest " + sum);
double sum2 = 0;
for (int i = 5000; i >= 1; i--) {
sum2 += 1.0 / i;
}
System.out.println("From smallest to largest " + sum2);
BigDecimal sum3 = BigDecimal.ZERO;
for (int i = 5000; i >= 1; i--) {
sum3 = sum3.add(BigDecimal.ONE.divide(BigDecimal.valueOf(i), 30, BigDecimal.ROUND_HALF_UP));
}
System.out.println("BigDecimal " + sum3);
prints
From largest to smallest 9.094508852984404
From smallest to largest 9.09450885298443
BigDecimal 9.094508852984436967261245533401
1 is an int constant, so 1 / (any int bigger than 1) is 0. You need to specify that you want a floating point division, by using 1.0 (float):
sum+=1.0/i;
^
That's a homework, then I just help you with a tip: be careful of variable types. 1/10 is equal to 0 if we consider it as an integer.
Try this instead:
sum += 1.0 / i;
How about:
public class Harmonic{
public static void main(String[] args){
double sum = 0;
for(int i=1; i<=5000; i++){
sum+=1.0/(double)i;
}
System.out.println(sum);
}
}
After the first iteration 1/i
will always be 0 since it's done in integer arithmetic. Therefore you're final answer will just be 1. Change it to 1.0/i
to get double arithmetic, and keep in mind that when you're loop finishes you may have a fair amount of error due to precision loss while using doubles. You can try it out and see how accurate it is though.
because i is an int so the division will be truncated... try putting sum+ = 1/(double)i
java-8 solution for calculating Harmonic sum:
public static double harmonicSum(int n) {
return IntStream.rangeClosed(1, n)
.mapToDouble(i -> (double) 1 / i)
.sum();
}
精彩评论