Question

I have two large long values, e.g. long a = 106951484895 and long b = 47666297253. I want to divide one by the other, while still retaining precision and accuracy. a / b gives just 2, which is neither precise nor accurate. (double)a / b returns 2.243754834308401 which is precise, but I don't know whether it is accurate. Is it accurate, or is there a better way?

Was it helpful?

Solution

If you check the calculation in Wolfram Alpha, you'll see that the exact result is
2.243754834308400900535121747859167616725725368773485418854923... Your figure of
2.243754834308401 is dead on. Unless you need more precision, the calculation with doubles will suffice.

OTHER TIPS

In Java there is a BigInteger class, for when you need unlimited precision using whole numbers. For decimal numbers, use BigDecimal

Wolfram Alpha will give you 2.243754834308400900535121747859167616725725368773485418854923..., and our figure is 2.243754834308401, which is same as

bigDecimal1.divide(bigDecimal2, MathContext.DECIMAL64)

If you will go for

bigDecimal1.divide(bigDecimal2, new MathContext(1000, RoundingMode.HALF_EVEN)))

You will get

2.24375483430840090053512174785916761672572536877348541885492361677904883097801043287594504
1050407263946829396490609763285697017511527160785819555506643456210143732768535294645618694
7909645722613183738163350810420038396599808994188248448801742297144651257940243013656347535
1346061895880989881427322957327423437070470786123178209350642720039431463073874604572487035
0881416301899886949878414127297558394219666911873273296141755170873372894249298571586701215
5058865276866526572281643300564007415077913939597358974242706109866167162174559269200972437
4468185209762552814414640557312348785977139301334520631262090283427956618755742143233766150
5750523038219597199472866720344664485953248792408356275728443143815091921547456137582778817
3173376404446432448382818379181981559569409501831858179303080342832602945081961262782040747
0742627855109348071601512026092932232568603874560325500767085983329631127368742840999544420
8119473080650114494849915293461361824567061678496514955637978679644265088391509259402889160

For more accuracy you can keep increasing the precision given in the MathContext constructor.

This RoundingMode.HALF_EVEN aka Banker's rounding is analogous to the rounding policy used for float and double arithmetic in Java.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top