This week's book giveaway is in the Java in General forum.
We're giving away four copies of Helidon Revealed: A Practical Guide to Oracle’s Microservices Framework and have Michael Redlich on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

casting from float to double gives undetermined result

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Proudly marching to the beat of a different kettle of fish... while reading this tiny ad
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic