0

I have ..

target = targetmax / difficulty

targetmax = 26959535291011309493156476344723991336010898738574164086137773096960

difficulty = 14484.162361

target = 26959535291011309493156476344723991336010898738574164086137773096960 / 14484.162361

target = 1861311315012765306929610463010191006516769515973403833769533170

So I attempted this in Java as

    double difficulty = 14484.162361;

    String targetmaxStr = "26959535291011309493156476344723991336010898738574164086137773096960";

    BigDecimal targetmaxd = new BigDecimal(targetmaxStr);

    BigDecimal difficultyd = new BigDecimal(difficulty);

    BigDecimal targetd = targetmaxd.divide(difficultyd, MathContext.DECIMAL128); 

    System.out.println("target : " + targetD);

It prints

target : 1.861311315012765229690386592708552E+63

I am really expecting value:

target = 1861311315012765306929610463010191006516769515973403833769533170

Jagdish
  • 231
  • 4
  • 18
  • 1
    It is not a duplicate of that question. – Matthew McPeak Sep 12 '17 at 21:44
  • @MatthewMcPeak I really believe that it is. The discrepancy is caused by the use of the `BigDecimal(double)` constructor - which is what that other question addresses. – Dawood ibn Kareem Sep 12 '17 at 21:45
  • You are right, it is a combination of issues. Creating `difficulty` from a double is creating an inaccuracy as are the issues I pointed out in my answer. I'll update my answer for completeness. – Matthew McPeak Sep 12 '17 at 21:49

1 Answers1

2

You have three problems.

First, use targetd.toPlainString()) to print the BigDecimal out avoiding scientific notation.

Second, you are limiting your precision too much by using MathContext.DECIMAL128. Try something like new MathContext(200) instead.

Third, as was debated in the comments, creating your BigDecimal from a double creates some precision issues. Create from a String instead to avoid those.

Here it is all together:

String targetmaxStr = "26959535291011309493156476344723991336010898738574164086137773096960";
BigDecimal targetmaxd = new BigDecimal(targetmaxStr);
BigDecimal difficultyd = new BigDecimal("14484.162361");
BigDecimal targetd = targetmaxd.divide(difficultyd, new MathContext(200)); 
System.out.println("target : " + targetd.toPlainString());

Result:

target : 1861311315012765306929610463010191006516769515973403833769533170.5181511669744807274464658288015444595719414139754270599065953124329244737606680298383048483144520034008751609022370030307892100271382756

Matthew McPeak
  • 17,705
  • 2
  • 27
  • 59