Logo

Programming-Idioms

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

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

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);
#include <math.h>
#include <stdio.h>
  double d = 3.14;
  double res;
  int e;

  res = frexp(d, &e);
  printf("%f %d\n",res,e);

New implementation...
< >
tkoenig