统计信息

  • 访问数:10947
  • 博客数:142
  • 建立时间:2008-01-05
  • 更新时间:2008-05-21
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P4Q7

2008-02-14 12:46:44

天气: 晴朗 心情: 高兴

/*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);
   
  }
}


 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd