Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the decimal number of a double

Tags:

java

math

I am working with a cos value which is represented in double. So my bounds are between -1.0 and 1.0, however for my work I am simply ignoring all negative variables.

Now I'd like to get the decimal number of this double number (sorry I couldn't find the literature term of this operation)

Basically with examples:

Assume that input is 0.12 then this could be written as 1.2 * 10^-1, what I am expecting to get is just the part where it is 10^-1

Another example is 0.00351, which can be written as 3.51 * 10^-3, so the expected result is 10^-3

I have developed this algorithm below but it's kind of quick and dirty. I was wondering whether is there any mathematical trick to avoid using a loop.

double result = 1;
while (input < 1.0) {
   input *= 10.0;
   result /= 10.0;
}

Also the above doesn't handle if input is 0.

I am using Java for coding if that helps.

like image 750
Sarp Kaya Avatar asked Mar 20 '23 10:03

Sarp Kaya


2 Answers

It appears you are looking for the base 10 exponent of the number - use Math.log10 to do this

 Math.log10(input)

e.g.

log10(100) = 2
log10(1e-5) = -5

etc.

You'll need to remember the base you've used (10 in this case)

like image 154
StuartLC Avatar answered Mar 22 '23 00:03

StuartLC


public class Tester {

    public static double lowbase(double v) {
        return Math.pow(10, Math.floor(Math.log10(Math.abs(v))));
    }   

    public static void main(String [] args){
        System.out.println(lowbase(0.12));
        System.out.println(lowbase(0.00351));
        System.out.println(lowbase(0));
        System.out.println(lowbase(-1));
    }   

}

Gives:

0.1
0.001
0.0
1.0

The abs is for handling the negative numbers, you may fiddle with that for a different take on negatives.

like image 44
perreal Avatar answered Mar 22 '23 01:03

perreal