Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there so many floats in the Android API?

The default floating point type in Java is the double. If you hard code a constant like 2.5 into your program, Java makes it a double automatically. When you do an operation on floats or ints that could potentially benefit from more precision, the type is 'promoted' to a double.

But in the Android API, everything seems to be a float from sound volumes to rectangle coordinates. There's a structure called RectF used in most drawing; the F is for float. It's really a pain for programmers who are casting promoted doubles back to (float) pretty often. Don't we all agree that Java code is messy and verbose enough as it is?

Usually math coprocessors and accelerators prefer double in Java because it corresponds to one of the internal types. Is there something about Android's Dalvik VM that prefers floats for some reason? Or are all the floats just a result of perversion in API design?

like image 325
Brian Avatar asked Mar 19 '10 06:03

Brian


People also ask

What is Float in android?

An object of type Float contains a single field whose type is float . In addition, this class provides several methods for converting a float to a String and a String to a float , as well as other constants and methods useful when dealing with a float .

Why are floating point numbers inaccurate in Javascript?

Because often-times, they are approximating rationals that cannot be represented finitely in base 2 (the digits repeat), and in general they are approximating real (possibly irrational) numbers which may not be representable in finitely many digits in any base.

What is the float in Java?

The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038.


2 Answers

On devices without an FPU, the single-precision floating point ops are much faster than the double-precision equivalents. Because of this, the Android framework provides a FloatMath class that replicates some java.lang.Math functions, but with float arguments instead of double.

On recent Android devices with an FPU, the time required for single- and double-precision operations is about the same, and is significantly faster than the software implementation. (The "Designing for Performance" page was written for the G1, and needs to be updated to reflect various changes.)

Incidentally, writing "2.5f" or "(float) 2.5" doesn't matter. Either way, javac knows you want a single-precision float constant, and that's what it generates. You can verify this by writing a sample program and examining the bytecode generated.

like image 181
fadden Avatar answered Nov 09 '22 03:11

fadden


Depending on the CPU there will be no Floating Point Unit (FPU). So it has to emulate the FPU in Software. this is faster for a Float than for a Double. Or if the Device has a FPU it will be probably also be faster with Floats.

like image 21
nuriaion Avatar answered Nov 09 '22 03:11

nuriaion