Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Possible loss of precision Date: Thu, 14 Nov 2013 18:31:53 -0500 Organization: A noiseless patient Spider Lines: 40 Message-ID: References: <87txfe22o1.fsf@golem.phantasia.org> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Thu, 14 Nov 2013 23:31:51 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="858a9d65d95f4ea4d355bd116aa2cdbf"; logging-data="10736"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+iaoXfa+0Dvyhn5wGs75FE" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Thunderbird/24.1.0 In-Reply-To: Cancel-Lock: sha1:jbuIxcs9Wz3V+xRsKlEPR4lNXPw= Xref: csiph.com comp.lang.java.programmer:26506 On 11/14/2013 6:03 PM, Gene Wirchenko wrote: > On Thu, 14 Nov 2013 20:39:42 +0100, Michael Jung > wrote: > >> ram@zedat.fu-berlin.de (Stefan Ram) writes: >>> char x = 'C' + 1; >>> x = x + 1; >>> in a block, one gets an error message >>> »possible loss of precision« >>> for »x = x + 1«. Ok, fair enough: »x + 1« has type »int«, >>> and precision is lost when assigning this to the variable x >>> of type char. >>> I was somewhat surprised, though, that »char x = 'C' + 1;« >>> does not yield an error, even though the type of »'C' + 1« >>> is int, too. Possibly, this time, the compiler can figure >>> out that the actual value still fits into a char. >>> But then, »int i = 2.0;« gives an error, even though the >>> compiler should see that »2.0« can be represented as an int. >> >> You are right that x+1 is "promoted" to int and the second assignment >> fails. In the other cases the compiler will follow JLS 15.28 => 5.2. >> This concerns constant expressions first and the second allows a >> narrowing in rare cases, of which the first line is one but the >> "int i = 2.0" isn't. > > Why isn't it though? Speculation: The fact that a floating-point expression happens to evaluate to a number with no fractional part doesn't mean the value "is" an integer. One reasonable view of FP is that a value is just a representative of a range of real values, namely, all those real values that round to the representative. In this view, converting 2.0 to 2 *does* lose precision, specifically, the amount of wiggle room. Then again, maybe the Java designers were just FP-wary. -- Eric Sosman esosman@comcast-dot-net.invalid