V
V
Vasya Pokryshkin2014-08-01 12:59:37
C++ / C#
Vasya Pokryshkin, 2014-08-01 12:59:37

How to find the mantissa of a decimal number?

What are the ways to find the mantissa of a number? In addition to dividing by 10 in a cycle and the decimal logarithm.
I would like to find an elegant and fast working solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mrrl, 2014-08-04
@akaChewy

Here "elegant" and "fast" are slightly contradictory requirements. The fastest way is to determine the number of characters by dividing in half for 3-4 comparisons:

double mantissa(int c){
  int a=abs(c);
  int b=1;
  if(a>=100000){
    if(a>=10000000){
      if(a>=1000000000) b=1000000000;
      else if(a>=100000000) b=100000000;
      else a=10000000;
    }else if(a>=1000000) b=1000000;
    else b=100000;
  }else{
    if(a>=100){
      if(a>=10000) b=10000;
      else if(a>=1000) b=1000;
      else a=100;
    }else if(a>=10) b=10;
  }
  return (double)c/b;
}

but such code can hardly be called beautiful.
A loop would be best, but not with division, but with integer multiplication by 10. But there you need to watch for overflow.
It is possible, of course, and through float. But there, after calculating the order, it will be necessary to raise 10 to the desired power, and the pow function may be too long for this.
double mantissa(int a){
  if(a==0) return 0;
  float f=a;
  int b=((*(int*)&f&0x7fffffff)-0x40cd3ed7)/0x019a7daf;
  double d=a*pow(0.1,b);
  if(fabs(d)>=10) d/=10;
  return d;
}

S
Sergey, 2014-08-01
@begemot_sun

Number float or double ?
Apparently you need to read: en.wikipedia.org/wiki/IEEE_floating_point#Basic_formats
and, based on the binary format of your type, find the mantis you need yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question