Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Alice

RoundoffError


Output.txt
RoundoffError.java

RoundoffError.java

public class RoundoffError {
	public static void main(String[] args) {
		float x = 1.0f;
		float y1 = 0.00000005f;
		float y2 = 0.00000006f;
		
		System.out.println("Adding a small number to 1");
		float z=x+y1;
		System.out.printf("%1.9f + %1.9f  = %1.9f\n",x, y1, z);
		z=x+y2;
		System.out.printf("%1.9f + %1.9f  = %1.9f\n\n",x, y2, z);
		

		System.out.println("Adding a small number to 1 a bunch of times");
		z = x;
		int n = 10000;
		for(int i=0;i<n;i++) {
			z = z + y1;
		}		
		System.out.printf("%1.9f + %1.9f*%d  = %1.9f\n",x, y1, n, z);
		
		z = x;
		n = 10000;
		for(int i=0;i<n;i++) {
			z = z + y2;
		}
		System.out.printf("%1.9f + %1.9f*%d  = %1.9f\n\n",x, y2, n, z);
		
		
		System.out.println("Adding a multiple of a small number to 1");
		z = x + y1*n;
		System.out.printf("%1.9f + %1.9f*%d  = %1.9f\n",x, y1, n, z);
		z = x + y2*n;
		System.out.printf("%1.9f + %1.9f*%d  = %1.9f\n\n",x, y2, n, z);
		

		System.out.println("(a-b)^2 == a*a - 2*a*b + b*b ?");
		float a = 1;
		float b = 0.0000005f;
		float c = (a-b);
		float cs1 = c*c;
		float cs2 = a*a - 2*a*b + b*b;

		System.out.printf("(%1.9f - %1.9f)^2 = (%1.9f)^2  = %1.9f\n",a, b, c, cs1);
		System.out.printf("(%1.9f - %1.9f)^2  = %1.9f\n",a, b, cs2);
		
		if(cs1==cs2) {
			System.out.println("They are the equal");
		} else {
			System.out.println("They are the not equal");
		}
	}
}