r/C_Programming • u/onecable5781 • Sep 01 '26
Converting fractions to integers
I have a double* which has the following entries:
0.3333333333333334
0.6666666666666668
0.1249999999999999
1Here, the last entry, 1, can be considered the right hand side of an inequality:
0.3333333333333334 x + 0.6666666666666668 y + 0.1249999999999999 z >= 1These numbers come from a numerical linear algebra library over which I don't have any control. What is the easiest way to "convert" this to the following equivalent inequality (subject to a user provided tolerance of what counts as an epsilon so that epsilon within an integer is to be counted as an integer)?
8 x + 16 y + 3 z >= 24Is there a package that does such conversion, if reasonably possible? I consider it unreasonably possible by multiplying everything in the original equation by a large enough power of 10. But I do not want that.
13
u/aioeu Sep 01 '26 edited Sep 01 '26
I would convert each of the coefficients to a rational number by using continued fractions. You can choose what accuracy you would like by cutting off this process just before the denominator exceeds a certain threshold. A continued fraction will always yield "best" rational approximations to a real number. With these coefficients, you're going to hit 1/3, 2/3 and 1/8 pretty quickly, with the rational approximations following these all having very large denominators.
Once you've got rational approximations, it's only a small amount of extra work to find the LCM of the denominators so you can convert everything to integers.
4
u/MyTinyHappyPlace Sep 01 '26
It’s tough that you don’t get the actual fractions but their nearest double values. Otherwise the GNU MP (https://gmplib.org/manual/Rational-Number-Functions) library could carry you a bit on your way
2
u/Educational-Paper-75 Sep 01 '26
By brute force multiplication of your 1/3, 2/3 and 1/8 by successive integers (2, 3, ...) until all are within epsilon of their floor values.
1
u/Forever_DM5 Sep 01 '26
Multiply by 10^n where n is the number of significant digits you want(your tolerance).
Apply Euclid’s algorithm to find the LCD then multiply the original equation by that.
1
u/dstroy0 Sep 01 '26
Sorry for pasting a ton of stuff, but this is a fun problem, I solve it this way, please ignore my dispatch and entry macros. What you want is to follow muto scale to u64, that will give you the fast pow10 we know how large and small these numbers can be represented path, which is exact from smallest normal to largest normal. (-1022 to +1023) someone else mentioned using pow10 already, this is taken to the extreme using language semantics forcing compiler behavior for opt, you don't need to reproduce this exactly for it to work the way you want, but this is one of the fastest methods available to perform the mutation/transform.