Disclaimer: this question may not have practical value, it's more of a puzzle/curiosity question.
In Java I can write the following code to programmatically find the size of int:
public static void main(String[] args)
{
int x = 1;
int count = 1;
while((x = x << 1) != 0)
{
count++;
System.out.println("x: " + x + ", " + count);
}
System.out.println("size: " + count);
}
Is there a similar way to programmatically find the size of Java's float?
To get the length of a float in Python:Pass the string to the len() function, e.g. len(result) . The len() function will return the length of the string.
Size: Float is of size 32 bits while double is of size 64 bits. Hence, double can handle much bigger fractional numbers than float. They differ in the allocation of bits for the representation of the number.
write the float into a ByteArrayOutputStream and get the length of the result.
import java.io.*;
class Test
{
public static void main(String[] args) throws Exception
{
ByteArrayOutputStream baos =new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
dos.writeFloat(0f);
System.err.println(baos.toByteArray().length);
}
}
$ javac Test.java
$ java Test
4
Java floats follow the IEEE floating point standard so you can easily inform yourself on the details. In a nutshell, there is no clean separation between the "used" and "unused" part of a float as it is with the two's complement integer encoding. The basic division is into sign bit, mantissa, and exponent. You may perhaps see what mantissa bits are used and what exponent bits are used, but it is far from a trivial task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With