This project has moved and is read-only. For the latest updates, please go here.

Conversion from double off by hundreds of orders of magnitude


When I convert the following double:

var d = Math.Pow(3, 1.0/3) + Math.Pow(5, 1/5.0); //approx 2.8564631326805037

like so:

var b = new BigRational(d);

I get an absurdly small BigRational:

6354532308320225 / 11235582092889474423308157442431404585112356118389416079589380072358292237843810195794279832650471001320007117491962084853674360550901038905802964414967132773610493339054092829768888725077880882465817684505312860552384417646403930092119569408801702322709406917786643639996702871154982269052209770601514008576

and so when I convert back to double it's waaaaay off:

var d2 = (double)b // approx 5.6557214889131024E-292

file attachments


jnm2 wrote Jun 11, 2014 at 5:37 PM

I have a fix for this. It's actually simple; they are raising the significand to the power of the exponent where they should be raising two to the power of the exponent and multiplying that to the significand.

My fix is much more efficient because it counts trailing zeros in the significand so that the initial conversion never needs simplification.

Compare public BigRational(Double value) in the file I have attached.

wrote Jun 11, 2014 at 5:40 PM

wrote Jun 11, 2014 at 5:46 PM

jnm2 wrote Jun 11, 2014 at 5:46 PM

My bad, left a line of test code in the file. Reuploading.

neremin wrote Apr 9, 2016 at 10:12 PM

Your fix made my day. Well done!