AdamWhiteHat / BigDecimal

An arbitrary-precision decimal (base 10) floating-point number class. Over 2.5 million downloads on NuGet!
MIT License
53 stars 15 forks source link

Negate wasn't passing the exponent to the BigDecimal constructor. #7

Closed AdamWhiteHat closed 2 years ago

AdamWhiteHat commented 2 years ago

Added more tests. 100% of tests pass now.

Protiguous commented 2 years ago

Good catch! I'll add it into the experimental branch.

Protiguous commented 2 years ago

Ah, I see why my version wasn't throwing on the test. It was already passing it to the multiply function. I'll have to test, but I think your version might be faster (less calculations) with the same result.

This is what I have atm, public static readonly BigDecimal MinusOne = new( -1 ); public static BigDecimal Negate( BigDecimal value ) => value * MinusOne;

AdamWhiteHat commented 2 years ago

Yeah, probably.

BigInteger.Negate flips the sign of a private int called _sign (e.g. _sign = - _sign), and that, in turn, emits a single IL op code: neg.

Whereas BigInteger.Multiply will instantiate a new object and perform long-hand multiplication--I see no special case to short circuit multiplication by -1.

Check out my Nth root code I recently added after this commit. Its really elegant. According to Wikipedia, Nth root for a floating point number is really simple: Find the Nth root of the mantissa, and divide the exponent by N.

I may add trigonometric function (sine, cosine, tangent) next/soon. Apparently the way to do trigonometric functions to arbitrary precision, digit by digit, is an algorithm called CORDIC. That will get you arbitrary precision tangent, then you can just convert the tangent to the sine/cosine for those. This works in/on radians only, but one can convert radian to/from degrees. I have a proof of concept working for tangent on doubles, I just need to convert it to arbitrary precision and then write methods to go from tangent -> sine and tangent -> cosine.

I looked at other BigDecimal libraries available, I don't think they even have Nth root available, definitely not trigonometric functions, so we are already ahead of them in terms of features.