
On Sun, Jan 13, 2008 at 01:08:49AM +0100, Henning Thielemann wrote:
Is there a fast and reliable way to compute the fraction of a floating point number?
no, and this has bothered me to the point I consider it a bug in the language spec that all 'rounding' style functions give back an integral type. These sort of operations are often used on floating point values when you want the same type out you put in, and in particular you want it to handle things like infinities and nan's properly which the conversion through integral does not (plus, these usually coorespond to a single machine instruction so are more 'primitive' in a sense and thus better building blocks for a RealFrac class). To alleviate this I added the following to the RealFrac class in jhc -- TODO Doubles class (Real a, Fractional a) => RealFrac a where .... ... -- new stuff added by jhc properFractionf :: a -> (a,a) truncatef, roundf :: a -> a ceilingf, floorf :: a -> a truncatef x = m where (m,_) = properFractionf x roundf x = fromInteger (round x) ceilingf x = if r > 0 then n + 1 else n where (n,r) = properFractionf x floorf x = if r < 0 then n - 1 else n where (n,r) = properFractionf x the meaning should be clear, they perform the same operation as their non f counterparts but maintain the same type. John -- John Meacham - ⑆repetae.net⑆john⑈