Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to get the fraction and exponent of a real number in Java

2 Answers

0 votes
public class FrexpExample {
    public static void main(String[] args) {
        double d = 3.14;
        
        int[] exponent = new int[1];
        double fraction = frexp(d, exponent);
        
        System.out.printf("fraction = %.6f exponent = %d%n", fraction, exponent[0]);
    }

    public static double frexp(double value, int[] exp) {
        if (value == 0.0) {
            exp[0] = 0;
            return 0.0;
        }
        long bits = Double.doubleToRawLongBits(value);
        int rawExp = (int)((bits >> 52) & 0x7FFL);

        if (rawExp == 0) { // subnormal
            value *= Math.pow(2, 54);
            bits = Double.doubleToRawLongBits(value);
            rawExp = (int)((bits >> 52) & 0x7FFL);
            rawExp -= 54;
        }

        exp[0] = rawExp - 1022;
        
        return value / Math.pow(2, exp[0]);
    }
}



/*
run:

fraction = 0.785000 exponent = 2

*/

 



answered Jun 30, 2025 by avibootz
0 votes
public class FrexpExample {
    public static double[] frexp(double value) {
        if (value == 0.0) {
            return new double[]{0.0, 0};
        }

        int exponent = Math.getExponent(value);
        
        // Adjust the exponent for the [0.5, 1.0) mantissa range
        int adjustedExponent = exponent + 1; 
        
        double mantissa = Math.scalb(value, -adjustedExponent);

        return new double[]{mantissa, adjustedExponent};
    }

    public static void main(String[] args) {
        double number = 3.14;
        double[] fraction = frexp(number);
        
        System.out.println("Original number: " + number);
        System.out.println("Mantissa (fraction): " + fraction[0]);
        System.out.println("Exponent: " + (int) fraction[1]);
        System.out.println("Reconstructed: " + (fraction[0] * Math.pow(2, fraction[1])));
    }
}


/*
run:

Original number: 3.14
Mantissa (fraction): 0.785
Exponent: 2
Reconstructed: 3.14

*/

 



answered Jun 30, 2025 by avibootz
...