Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #204 Return fraction and exponent of a real number

Given a real number a, print the fractional part and the exponent of the internal representation of that number. For 3.14, this should print (approximately)

0.785 2

#include <math.h>
#include <stdio.h>
  double d = 3.14;
  double res;
  int e;

  res = frexp(d, &e);
  printf("%f %d\n",res,e);
using System;
static void Frexp(double value, out double mantissa, out int exponent)
{
    var bits = BitConverter.DoubleToInt64Bits(value);
    var negative = (bits & (1L << 63)) != 0;
    exponent = (int)((bits >> 52) & 0x7FFL);
         Console.WriteLine("nt2: " + exponent);
    var mantissaLong = bits & 0xFFFFFFFFFFFFFL;

    if (exponent == 0)
    {
        exponent++;
    }
    else
    {
        mantissaLong |= 1L << 52;
    }

    exponent -= 1075;

    if (mantissaLong == 0)
    {
        mantissa = 
a = 3.14
print *,fraction(a), exponent(a)
import "math"
fmt.Println(math.Frexp(a))
function frexp(a) {
    exponent = ( Math.floor(Math.log(a, 2)) + 1 )
    mantissa = ( a * Math.pow(2, -a) )

    return [ mantissa, exponent ]
}
local function frexp(a)
	return math.frexp(a)
end
uses math;
var
  d: double;
  Mantissa: double;
  Exponent: integer;
begin
  d := 3.14;
  frexp(d, Mantissa, Exponent);
  writeln('Mantissa: ',Mantissa:6:5,', Exponent: ',Exponent);
end.
use POSIX qw(frexp);
my ($mantissa, $exponent) = frexp $a;
printf "%f %d\n", $mantissa, $exponent;
import math
print(math.frexp(a))
puts Math::frexp(a)
let sign = if a < 0.0 { a = -a; -1 } else { 1 };
let exponent = (a + f64::EPSILON).log2().ceil() as i32;
let fraction = a / 2.0f64.powi(exponent);

New implementation...
< >
tkoenig