Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically finding the size of float

Tags:

java

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?

like image 388
shrini1000 Avatar asked Jul 13 '12 07:07

shrini1000


People also ask

How do you find the length of a 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.

What is the size of float and double in Java?

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.


2 Answers

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
like image 176
Pierre Avatar answered Oct 06 '22 16:10

Pierre


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.

like image 25
Marko Topolnik Avatar answered Oct 06 '22 15:10

Marko Topolnik