69750

Dividing a BigIntegers to return double

Question:

I want to calculate the slope of a line.

public sealed class Point { public System.Numerics.BigInteger x = 0; public System.Numerics.BigInteger y = 0; public double CalculateSlope (Point point) { return ((point.Y - this.Y) / (point.X - this.X)); } }

I know that BigInteger has a DivRem function that returns the division result plus the remainder but am not sure how to apply it to get a double. The numbers I'm dealing with are <strong>far far</strong> beyond the range of Int64.MaxValue so the remainder itself could be out of range to calculate by conventional division.

<strong>EDIT</strong>: Not sure if it helps but I'm dealing with only positive integers (>=1).

<strong>IMPORTANT</strong>: I only need a few decimal points of precision (5 should be good enough for my purpose).

Answer1:

The <a href="http://bcl.codeplex.com/wikipage?title=BigRational&referringTitle=Home" rel="nofollow">BigRational</a> library has a conversion operator to double.

Also, remember to return infinity as a special case for a vertical line, you'll get a divide by zero exception with your current code. Probably best to just calculate the X1 - X2 first, and return infinity if it's zero, then do the division, to avoid redundant operations.

Answer2:

Get <a href="http://bcl.codeplex.com/wikipage?title=BigRational&referringTitle=Home" rel="nofollow">BigRational</a> from Codeplex. Its part of Microsoft's <a href="http://bcl.codeplex.com/" rel="nofollow">Base Class Library</a>, so it's a work-in-progress for .Net. Once you have that, then do something like:

System.Numerics.BigInteger x = GetDividend() ; System.Numerics.BigInteger y = GetDivisor() ; BigRational r = new BigRational( x , y ) ; double value = (double) r ;

Dealing with the inevitable overflow/underflow/loss of precision is, of course, another problem.

Since you can't drop the BigRational library into your code, evidently, the other approach would be to get out the <a href="https://rads.stackoverflow.com/amzn/click/com/0201896842" rel="nofollow">right algorithms book</a> and roll your own...

The easy way, of course, of "rolling one's own" here, since a rational number is represented as the ratio (division) of two integers, is to grab the explicit conversion to double operator from the BigRational class and tweak it to suit. It took me about 15 minutes.

About the only significant modification I made is in how the sign of the result is set when the result is positive or negative zero/infinity. While I was at it, I converted it to a BigInteger extension method for you:

public static class BigIntExtensions { public static double DivideAndReturnDouble( this BigInteger x , BigInteger y ) { // The Double value type represents a double-precision 64-bit number with // values ranging from -1.79769313486232e308 to +1.79769313486232e308 // values that do not fit into this range are returned as +/-Infinity if (SafeCastToDouble(x) && SafeCastToDouble(y)) { return (Double) x / (Double) y; } // kick it old-school and figure out the sign of the result bool isNegativeResult = ( ( x.Sign < 0 && y.Sign > 0 ) || ( x.Sign > 0 && y.Sign < 0 ) ) ; // scale the numerator to preseve the fraction part through the integer division BigInteger denormalized = (x * s_bnDoublePrecision) / y ; if ( denormalized.IsZero ) { return isNegativeResult ? BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000)) : 0d; // underflow to -+0 } Double result = 0 ; bool isDouble = false ; int scale = DoubleMaxScale ; while ( scale > 0 ) { if (!isDouble) { if ( SafeCastToDouble(denormalized) ) { result = (Double) denormalized; isDouble = true; } else { denormalized = denormalized / 10 ; } } result = result / 10 ; scale-- ; } if (!isDouble) { return isNegativeResult ? Double.NegativeInfinity : Double.PositiveInfinity; } else { return result; } } private const int DoubleMaxScale = 308 ; private static readonly BigInteger s_bnDoublePrecision = BigInteger.Pow( 10 , DoubleMaxScale ) ; private static readonly BigInteger s_bnDoubleMaxValue = (BigInteger) Double.MaxValue; private static readonly BigInteger s_bnDoubleMinValue = (BigInteger) Double.MinValue; private static bool SafeCastToDouble(BigInteger value) { return s_bnDoubleMinValue <= value && value <= s_bnDoubleMaxValue; } }

Answer3:

This does not deal with negative but hopefully give you a start.

double doubleMax = double.MaxValue; BigInteger numerator = 120; BigInteger denominator = 50; if (denominator != 0) { Debug.WriteLine(numerator / denominator); Debug.WriteLine(numerator % denominator); BigInteger ansI = numerator / denominator; if (ansI < (int)doubleMax) { double slope = (double)ansI + ((double)(numerator % denominator) / (double)denominator); ; Debug.WriteLine(slope); } }

Recommend

  • Can't authenticate with custom PASSWORD_HASHERS
  • Configuring environment variables for static web site on AWS S3
  • python-requests with multithreading
  • How do I enable C# scripting in VS 2015?
  • Android Studio doesn't show options for create android projects
  • Alternate locations for javax.comm.properties in Windows
  • Programmatically Get the Incoming/Outgoing COM Bluetooth Port.How can do it in Windows Mobile 6 App
  • How to EXCLUDE MasterPage items when bulk exporting all text Frames
  • What do folks use app/services/ in rails applications
  • Python multiprocessing: can I reuse processes (already parallelized functions) with updated global v
  • Lookup song by ISRC in Apple Music/iTunes
  • Git objects SHA-1 are file contents or file names?
  • password_hash() not working [closed]
  • How to hide 'Add To Cart' for variable products, but keep product variations visible
  • Handle tunneled custom routed event
  • List using with references, changes behavior when used as a member
  • Send HTML Mail with Unicode
  • date changes on export kendoGrid
  • How to move to lines with the same indentation in Visual Studio Code
  • How to process remote XML files with XSLT
  • Django REST framework - HyperlinkedRelatedField with additional parameter
  • Keep rows with certain values always at the bottom while sorting in jquery tablesorter plugin
  • Ruby on Rails: Get mediaplayer information (iTunes, TRAKTOR, Cog; current song + playlist)
  • All Event listing on specified date in Google Calender api (V3) in java?
  • Ajax call on Multiple selection in Select box
  • Add font awesome icon to custom add to cart button in Woocommerce 3
  • How to make 100% div height between header and footer?
  • Comparing variables with strings bash
  • Cloud Code: Creating a Parse.File from URL
  • Terminal run dalvikvm with am.jar
  • How to handle div that is created dynamically in a table
  • How to get rgb from transparent pixel in js
  • Make checkout phone field optional for specific countries in WooCommerce
  • Python Flask - GUI for client
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • Write to .csv file with PHP (Commas in Data Error)
  • ReferenceError: TextEncoder is not defined
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}
  • Time Complexity of Fibonacci Algorithm [duplicate]