casting from float to double gives undetermined result
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
public class test{
public static void main( String args[] ){ float A = 1.0F / 3.0F ; double d=1.0 / 3.0 ; 1. System.out.println("d="+d); 2 System.out.println("before cast A= "+A); //After casting 3 System.out.println("after cast A="+(double)A); 4 System.out.println("AA="+A*7.0); 5 System.out.println("AAA="+A*7.0F); 6 if( ( A * 7.0f == 1.0F )) System.out.println( "Equal" ); else System.out.println( "Not Equal" ); } } At line 3 when we type cast float to double ,few additional digits are added to the result.See the diff in result at line 2 And line 3.But atually i feel this should not happen .Please anybody give me reason for that.
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
Double can hold higher precision values than float because of its size. Naturally the value of 1/3 stored as a double will hold more digits than 1/3 stored as a float. Hence the results are different!! Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).