0

I have been looking through the Math library but I cannot seem to find a method that will double a number and return it.

I need something that will do num+=num

Of course the above will work but once the numbers get large, it no longer does what I need, even if I use a long instead of an int.

Or is it perhaps the data type rather than a method that I need to change?

I found a solution.

 BigInteger num = new BigInteger("1");
 num = num.add(num);

When reading about BigInteger it said it was immutable so I took that as not being able to change the value. I think I need a better understanding of immutable.

WeVie
  • 568
  • 2
  • 9
  • 25

4 Answers4

1

There are float, double, BigInteger and BigDecimal.

  • float has less precision than double

  • float AND double both aren't infinite

  • BigInteger can hold infinite big values (only integers, no comma!)

  • BigDecimal is the same as BigInteger, but also can have decimals after the comma, i.e. 3.14

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
1

If you use double:

Math.scalb(num, 1)
NerosE
  • 362
  • 3
  • 5
1
 BigInteger num = new BigInteger("1");
 num = num.add(num);
WeVie
  • 568
  • 2
  • 9
  • 25
-2

This is possibly the second-most trivial question I have ever seen.

public BigInteger doubleIt(BigInteger num)
{
    return num.multiply(BigInteger.valueOf(2));
}

public BigDecimal doubleIt(BigDecimal num)
{
    return num.multiply(BigDecimal.valueOf(2));
}

public double doubleIt(double num)
{
    return num*2.0;
}

public long doubleIt(long num)
{
    return num*2;
}

Most trivial question is here.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Yeah, because doubles have infinite precision... – vanza Nov 12 '14 at 22:30
  • @vanza I haven't claimed any such thing. The OP may want a result that can't be represented by a datatype in the language, but that doesn't mean he can get it. – user207421 Nov 12 '14 at 22:39
  • 2
    You may want to read the part where he wrote "as the numbers get large"... `double` can represent large numbers but you lose a lot of precision in the process, so your solution is kinda useless for what he wants. So, not as trivial as you may suggest (even though the correct answer is, indeed, sort of trivial). – vanza Nov 12 '14 at 22:41