1

I am new to Java programming. I am calculating the travel speed in a specific distance, but when I get to trillions, I'm not sure what to do.

I've already tried putting 'L' on the last part of the value, however, I also remember that long data type is limited to 4 trillion so I'm getting this error:

Error:(22, 58) java: illegal character: '\u202c'

double speed = 299792;
long distance= 41320000000000‬L;
long temp = distance/speed; 

I was expecting the result to be 137828894.70. But I only get the error. I've been searching for answers since yesterday and I got no solution to this.

EDIT

I was able to figure things out, thank you for everyone's help! My code is now working and as follows:

BigDecimal distance= new BigDecimal("41320000000000");
BigDecimal speed = new BigDecimal("299792");
BigDecimal travelSpeed = distance.divide(speed, BigDecimal.ROUND_HALF_UP);
Neil
  • 65
  • 7

1 Answers1

6

Just as a general idea, if you are in the trillions you should probably choose different units :D

Take a look at the BigInteger class. Example usage:

import java.math.BigInteger;
        BigInteger large=new BigInteger("432");
        BigInteger larger=new BigInteger("41092380192841098439038490134");
        BigInteger product=larger.multiply(large);
        System.out.println(product);

Output:

17751908243307354525664627737888

Further JavaDocs for reference: https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html

PS. BigIntegers are "infinite" precision. So aside from weird numeric edgecases like +-infinity, +-NaN and +-zero you will never suffer unusual rounding errors or overflow errors. The only exception is integer division, which truncates the floating point.

PPS. BigIntegers are actually not infinitely precise. Under-the-hood, they can be thought of as represented by an int array for the digits. And arrays are limited by the Integer type bounds. I'm too lazy to figure this out, but a general guide is, and I would like to be quoted on this:

DONT USE NUMBERS GREATER THAN 10^(10^10).

But you already knew that :P

PPPS. It seems someone did the calculations for me. So (10^(10^10)) is NOT the most accurate figure!

@arshajii (third comment on https://stackoverflow.com/a/18444371/9609025) says that it is (2^32)^(2^31-1). This is a very big number!

mackycheese21
  • 884
  • 1
  • 9
  • 24
  • Strictly speaking, your "infinite" precision is incorrect. The precision is limited by 1) available memory, and 2) the largest size of an `int[]` allowed by the JVM spec. (But if you intend infinite in quotes to mean "almost" infinite ...) – Stephen C Jun 18 '19 at 03:39
  • There is an answer to the question. It would be better if you look at the answer and try. https://stackoverflow.com/questions/18444337/what-variable-type-can-i-use-to-hold-huge-numbers-30-digits-in-java – Lahiru Wijesekara Jun 18 '19 at 04:22