Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!usenet.ukfsn.org!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: floating point Date: Tue, 24 Jul 2012 20:34:47 +0000 (UTC) Organization: UK Free Software Network Lines: 50 Message-ID: References: NNTP-Posting-Host: 84.45.235.129 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: localhost.localdomain 1343162087 11813 84.45.235.129 (24 Jul 2012 20:34:47 GMT) X-Complaints-To: usenet@localhost.localdomain NNTP-Posting-Date: Tue, 24 Jul 2012 20:34:47 +0000 (UTC) User-Agent: Pan/0.135 (Tomorrow I'll Wake Up and Scald Myself with Tea; GIT 30dc37b master) Xref: csiph.com comp.lang.java.programmer:16313 On Tue, 24 Jul 2012 13:01:11 -0700, markspace wrote: > On 7/24/2012 12:57 PM, bob smith wrote: >> I can never remember this. >> >> Let's say you have an integer and a float in an operation. Is the >> result always a float? > > > You can just try this to see what you get, or read the JLS. From > memory, I'm 90% sure that ints will be promoted to floats. I'm not sure > how order of operations affects this. In the expression (1+1)/2.0f, > does the addition use floats or ints? I'm not sure, but I think ints. I think this: $ cat MathTest.java public class MathTest { public static void main(String[] args) { double x = (9 / 2) / 5; System.out.println("x = " + x); double y = (9 / 2) / 5.0; System.out.println("y = " + y); double z = (9 / 2.0) / 5.0; System.out.println("z = " + z); } } $ javac MathTest.java $ java MathTest x = 0.0 y = 0.8 z = 0.9 shows pretty conclusively that widening from int to double isn't done until the last possible moment. The calculation of x is entirely integral, with widening to double only occurring at the assignment. Calculating y can only produce that result if the first division was integral and its result was then widened to double before the second division. And, of course, the z calculation was entirely done as floating point -- martin@ | Martin Gregorie gregorie. | Essex, UK org |