Topic: scale() in standard library, and class fixed


Author: sean@delta.com (Sean L. Palmer)
Date: 1996/08/14
Raw View
I've noticed the glaring omission of a scale() function in the standard
library, for integers

int scale(int n, int multiplyby, int thendivideby);

long scale(long n, long multiplyby, long thendivideby);

and might as well:

double scale(dobule n, double multiplyby, double thendivideby);

the purpose, of course, is to use an intermediary storage that won't get
overflowed (twice the size of the parameter type's size)

Many cpu's support this directly. Where it doesn't, it can be faked rather
easily.

The main use for this that I personally can think of is for doing
fixed-point integer math.

For that matter, it seems to me that some kind of fixed-point class would
be a nice addition to the standard library, right up there with complex. On
platforms that don't deal well with integer math, it could be internally
represented as a float. On platforms that have a hard time with floating
point, or that have hardware support for it (like x86), it would be done
using integer fixed-point.


This sounds like a great idea to me.

I have a generic fixed-point template class (will be much better when I get
member templates) that loses a lot of precision due to the lack of scale().
 I have to use processor-specific inline assembly to keep precision, or
convert to float (which is slow on many platforms and defeats the purpose
of a fixed-point class)

So we really need at least one of the above items.

If we can't get a standard fixed-point class, at least the following two
functions need to be added to the standard library:

long multiply_and_shift_right(long a, long b, unsigned shifts);

long shift_left_and_divide(long num, long denom, unsigned shifts);

which are similar to scale() in that they use a larger temporary store.
They could be implemented very efficiently on a great many platforms, and
would make a platform-independent fixed-point class possible.


[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]