Simon H
Simon H

Reputation: 374

How to parse the division of two very large numbers into a double?

I have a geometric algorithm which takes as input a polygon. However, the files I am supposed to use as input files store the coordinates of the polygons in a rather peculiar way. Each file consists of one line, a counterclockwise sequence of the vertices. Each vertex is represented by its x and y coordinates each of which is written as the quotient of two integers int/int. However, these integers are incredibly large. I wrote a program that parses them from a string into long long using the function std::stoll. However, it appears that some of the numbers in the input file are larger than 2^64.

The output coordinates are usually quite small, in the range 0-1000. How do I go about parsing these numbers and then dividing them, obtaining doubles? Is there any standard library way of doing this, or should I use something like the boost library?

Upvotes: 2

Views: 176

Answers (2)

Jeffrey
Jeffrey

Reputation: 11400

If you are after a ratio of two large numbers as string, you can shorten the strings:

"194725681173571753193674" divided by "635482929374729202" is the same as

"1947256811735717" divided by "6354829293" to at least 9 digits (I just removed the same amount of digits on both sides). Depending on the needed precision, this might be the simplest solution. Just remove digits before converting to long long.

Upvotes: 2

eerorika
eerorika

Reputation: 238301

You can parse the inputs directly into a long double I believe. However, that approach will introduce precision errors. If precision is important, then avoid this.

A general solution for precise results is to represent the large integer with an array of integers where one integer represents the lower order bytes, next integer represents the larger bytes etc. This is generally called arbitrary precision arithmetic.

Is there any standard library way of doing this

No, other than basic building blocks such as vector for storing the array.

or should I use something like the boost library?

That's often a good place to start. Boost happens to have a library for this.

Upvotes: 1

Related Questions