View Full Version : comparing fractions
does anyone know of a good, existing function (or class) that compares fractions? Or will I have to build on something myself?
All my search has turned up is basic operations (+-/x) with fractions, which is a good starting point, but not what I want at the end of the day.
requirements:
given an array of fractions and/or mixed numbers (pref. in the format x, y/z, and x-y/z), can:
find which of two selections is greater/lesser
find which value(s) are closest to a selection
find all values in a given range (e.g., +1) from a selection
thanks in advance. I have a pretty good idea how I could code a class like this, but I'd rather not reinvent the wheel if I don't have to. :cool:
djr33
02-19-2010, 04:52 AM
I could write all of this for you if you want, though I'd need to find some time to do it.
I don't know of any way to do all of this.
HOWEVER, I don't really see the point. Create a fraction parser that makes it a decimal. Then work with the decimal. That's a lot easier.
well, I could do it too. I just wanted to see if anyone knew of something that already existed. and then I wouldn't have to.
thanks anyhow :)
djr33
02-19-2010, 06:48 AM
As I said, the trick is converting to decimals. Once you've done that everything else is easy.
The other problem is that I'm not sure how you can represent fractions in PHP: are you having them entered as strings? That makes everything more confusing and a bit harder (perhaps for "security" or at least error correction).
I expect that there are probably math libraries out there, but that since this is not so complex (compared to something like calculus) it might be more trouble to get from that what you need than just writing it.
Aside from dealing with input/converting to decimals, which I doubt you'll find a library for (that will be just "plug and play"), the rest should be pretty fast to write. It's basically just loops and looking to see if something is a match.
yeah, most of the classes I've found are pretty big heaps of code, most of which I'd never touch for this application.
yes, I'm having them entered as strings, at least that's the plan for the moment. They're values from a database (product dimensions) and a single string (while requiring some extra processing here) seems to create the least coding overhead overall. I thought about storing the whole number, numerator and denominator in separate fields, but I think that would be more of a pain than it's worth - especially for the client, who has to be able enter the info easily when things get updated.
SO, I think everything will be copied (retaining the original value/format for output) split up, converted into an improper fraction, then converted to decimal and operated on.
thanks!
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.