GWT strange code generation on float numbers

85 views
Skip to first unread message

Andrey Korzhevskiy

unread,
Feb 8, 2012, 9:54:09 AM2/8/12
to google-we...@googlegroups.com
Hello everyone,

I found interesting issue. Suppose I have this java code:

float f = 0.000001f;
someFunc(f)

which is generated by GWT into js code, something like that

someFunc(9.9534e-7) 


So my question is: if GWT sees constant in code why it processes this constant so strange? I expect to see in generated js this call: someFunc(0.000001)
Is there some complex float numbers processing in gwt-dev?


Thank you, 
Andrew

Steve

unread,
Feb 20, 2012, 10:46:01 AM2/20/12
to Google Web Toolkit
My guess is it's because .000001 cannot be expressed exactly as a
float. Like base 10 cannot express 1/3, IEEE floats have trouble with
1/10 and derivatives.

Steve

Alan Chaney

unread,
Feb 20, 2012, 11:10:13 AM2/20/12
to google-we...@googlegroups.com
On 2/20/2012 7:46 AM, Steve wrote:
> My guess is it's because .000001 cannot be expressed exactly as a
> float. Like base 10 cannot express 1/3, IEEE floats have trouble with
> 1/10 and derivatives.
>
> Steve
Yes, that's right, 0.000001f is not exactly representable with an IEEE
floating point number. I suspect that the OP's original 9.9534e-7 is the
closest a 64 bit FP number can get to 0.000001f. Its one reason why you
must be very careful with expressions like:

if (fpnumber == 0.000001f) then

And, of course, the original java.lang.Float gets converted to a JS
equivalent which is (almost) the same as a java.lang.Double in JS - but
will still have the same precision when emulated in hosted mode - so,
beware!

In my code I rarely, if ever, use floats anymore, especially if I think
that they are going to be used in GWT. The issues of additional
serialization payload are best solved by compression.

Alan

Andrey Korzhevskiy

unread,
Feb 20, 2012, 3:10:10 PM2/20/12
to google-we...@googlegroups.com
.000001 can be expressed in JS floating number. The thing is not in IEEE and runtime number representation. The thing is in that literal constant should not be changed.
I mean if in Java code I see   'float myNum = 0.000001', I expect to see it in generated JS as 'var myNum = 0.000001'

Steve

unread,
Feb 22, 2012, 8:55:28 AM2/22/12
to Google Web Toolkit
I don't think javascript is immune to this ...

http://stackoverflow.com/questions/588004/is-javascripts-math-broken

I just tried .1 + .2 at jsbin and got 0.30000000000000004

From the OP I assume the substitution for var f is not just a string
replacement; the literal is evaluated and during the evaluation the
number gets changed to something IEEE can handle.

Steve

On Feb 20, 3:10 pm, Andrey Korzhevskiy <a.korzhevs...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages