我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*P4Q7
* Name:Wang Chaoran
* Description:(Demonstrating cancellation errors)
* A cancellation error occurs when you are manipulating
* a very large number with a very small number.
* The large number may cancel out the smaller number.
* For example, the result of 100000000.0 + 0.000000001 is
* equal to 100000000.0. To avoid cancellation errors and
* obtain more accurate results, carefully select the order of computation.
* For example, in computing the following series, you will obtain more
* accurate results by computing from right to left rather than from left to right:
* Write a program that compares the results of the summation of the preceding series,
* computing from left to right and from right to left with n = 50000.
*/
import java.util.Scanner;
public class P4Q7
{
public static void main(String[] args)
{
//Create scanner
Scanner scan = new Scanner(System.in);
System.out.println("Please input n(50000): ");
double n = scan.nextDouble();
double sum1 = 0,sum2 = 0;
//compute the sums
for(double i=n;i>=1;i--)
{
sum1 += 1/i;
}
for(double i=1;i<=n;i++)
{
sum2 += 1/i;
}
System.out.println("computing from left to right: "+sum2);
System.out.println( "computing from right to left: "+sum1);
}
}
导入论坛查看(51)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing