/* float_number.java
*
*   Examine floating point numbers
*
*/


public class float_number {
	public float v;
	public int sign;
	public int exponent;
	public int significand;

	public void from_number()
	{
		int iv = Float.floatToRawIntBits(v);
		sign = iv>>31;
		significand = iv&0x7fffff;
		exponent = (iv>>23)&0xff;
	}
	

	public static float to_number(int sign, int exponent, int significand)
	{
		int iv;
		iv = ((sign&1)<<8) | (exponent&0xff);
		iv = (iv<<23) | (significand&0x7fffff);
		return Float.intBitsToFloat(iv);
	}		

	public void print_number()
	{
		from_number();
		System.out.printf("%d %2x %6x  %20.14g\n",sign,exponent,significand,v);
	}

	public static void main(String arg[])
	{
		int i;
		float_number f, g;
		f = new float_number();
		for (i=0; i<=32; i++) {
			System.out.printf("number %2d:   ",i);
			f.v = i;
			f.print_number();
			f.from_number();
			float v = float_number.to_number(f.sign,f.exponent,f.significand);
			if (f.v!=v) System.out.printf("*** conversion failed ***\n");
		}
		System.out.printf("\n\n");
		System.out.printf("number 1/2: "); f.v = 0.5f; f.print_number();
		System.out.printf("number 1/4: "); f.v = 0.25f; f.print_number();
		System.out.printf("number 1/10:  "); f.v = 0.10f; f.print_number();
		System.out.printf("FLT_EPSILON  ");
		f.v = float_number.to_number(0,127,1)-float_number.to_number(0,127,0);
		f.print_number();
		System.out.printf("\n\n");

		float error;
		f.v = 0.0f;
		float v = 0.1f;
		for (i=0; i<10; i++) f.v += v;
		error = Math.abs(f.v-1.0f);
		System.out.printf("0.1 added 10 times:        error (%8.2e) ",error);
		f.print_number();
		f.v = 0.0f;
		v = 0.01f;
		for (i=0; i<100; i++) f.v += v;
		error = Math.abs(f.v-1.0f);
		System.out.printf("0.01 added 100 times:      error (%8.2e) ",error);
		f.print_number();
		f.v = 0.0f;
		v = 0.001f;
		for (i=0; i<1000; i++) f.v += v;
		error = Math.abs(f.v-1.0f);
		System.out.printf("0.001 added 1,000 times:   error (%8.2e) ",error);
		f.print_number();
		f.v = 0.0f;
		v = 0.0001f;
		for (i=0; i<10000; i++) f.v += v;
		error = Math.abs(f.v-1.0f);
		System.out.printf("0.0001 added 10,000 times: error (%8.2e) ",error);
		f.print_number();

		System.out.printf("\n\n");
		for (i=0; i<4; i++) {
			f.v = float_number.to_number(0,i,0);
			f.print_number();
		}

		System.out.printf("\n\n");
		f.v = float_number.to_number(0,0xff,0); f.print_number();

		for (i=0; i<4; i++) {
			f.v = float_number.to_number(0,0xff-i,0x7fffff);
			f.print_number();
		}
	}
}
/*
	int i;
	int sign, exponent;
	long mantissa;
	double error;
	NUMBER f, g;

	return 0;

*/



