473,765 Members | 2,121 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit fiddling calculating fraction

Hello,

I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?

Jan 5 '07 #1
22 2086

<do*********@gm ail.comwrote in message
news:11******** **************@ v33g2000cwv.goo glegroups.com.. .
Hello,

I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?
It isn't clear what you are doing. Based on the comments this
returns A or zero. Also, the parantheses do make a difference.
Jan 5 '07 #2
Sorry for being unclear. This is maybe better?

ushort f ( ushort valueA, ushort valueB) {
float fraction = valueB / 31.0;
return (ushort)(valueA * fraction);
}

Only that I want to avoid using floating point operations and
division/multiplication.

Jan 5 '07 #3
do*********@gma il.com writes:
I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}
C.l.c Guidelines suggest posting a complete program. We have to guess
what ushort is. This is not as easy as you probably think since what
you have written above makes no sense if we assume

typedef unsigned short ushort;
I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
If we believe the block comment about the possible values in valueB, then

return valueB == 31;

will do the same as the return statement you wrote. If you put the
parentheses in by mistake (thinking that it made no difference) then
a divide is probably the way.

Of course, it is more likely that you want to be dividing by 32. In
that case a shift will be faster but the compiler will probably do that
for you anyway.

Write the simples clearest code and optimise it for speed only if you
find it to be a problem.

--
Ben.
Jan 5 '07 #4
do*********@gma il.com a écrit :
Hello,

I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?
Any division by a signed constant can be replaced by a
much cheaper multiplication and some shifts. For instance,
for the code above, the lcc-win32 compiler will not
generate a division by 31 but the following code:

movzwl 8(%ebp),%edi ; valueA-->edi
movzwl 12(%ebp),%eax ; valueB->eax
movl $-2078209981,%edx
movl %eax,%ecx ; save valueB for later
imull %edx ; multiply valueB * -2078209981
addl %ecx,%edx ; add valueA to high word
sarl $4,%edx ; shift right 4
sarl $31,%ecx ; shift left 31
subl %ecx,%edx ; subtract the result to valueB
movl %edx,%eax ; high word is result of division by 31
imull %eax,%edi ; multiply by valueA
movzwl %di,%eax ; cast to unsigned short and set return value

You see? No division. I would say you leave the optimization
to the compiler.

jacob
Jan 5 '07 #5
<do*********@gm ail.comwrote in message
news:11******** **************@ v33g2000cwv.goo glegroups.com.. .
Hello,

I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.

Etc.
If I'm understanding your problem correctly, it is the standard rational
approximation problem with the denominator fixed.

Generally, you seek to approximate f(x) = r * x by g(x) = (h * x) div k;
where r and x are real, and h and k are integers.

You generally seek to choose h/k as close as possible to r.

There are three basic strategies.

#1: You can choose k as a power of 2 so that the mapping is

g(x) = (h * x)/2^q

where of course the division is handled by shifting.

#2: You can use an arbitrary h and k, which normally doesn't work out badly
since most processors have efficient integer multiplication and division
instructions.

Choosing h/k as close as possible to an arbitrary r isn't as easy as it
sounds. There is an O(log N) technique using number theory and continued
fractions. I'll be glad to send you a technical paper if you e-mail me
directly at dt*@e3ft.com. For example, the best approximation to PI with 16
bit h,k is 65298 / 20785. Finding such an approximation in 32 or 64 bits is
very hard if you don't know how to do it O(log N).

#3: You can sometimes use addition to implement the multiplication. For
example, if h is 11 and k is 4:

two_times = x + x;
four_times = two_times + two_times;
eight_times = four_times + four_times;
eleven_times = x + two_times + eight_times;
result = eleven_times >2;

Those are the three basic techniques.

Any look attractive to you?

Dave.
Jan 6 '07 #6
do*********@gma il.com wrote:
>
I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?
Try the following:

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char **argv)
{
int num, approx, bestnum, bestdenom;
int lastnum = 500;
double error, leasterr, value, criterion, tmp;
char *eptr;

value = 4 * atan(1.0);
if (argc 2) lastnum = strtol(argv[2], NULL, 10);
if (lastnum <= 0) lastnum = 500;
if (argc 1) {
tmp = strtod(argv[1], &eptr);
if ((0.0 >= tmp) || (tmp INT_MAX) || (ERANGE == errno)) {
puts("Invalid number, using PI");
}
else value = tmp;
}
criterion = 2 * value * DBL_EPSILON;
puts("Usage: ratvalue [number [maxnumerator]]\n"
"number defaults to PI, maxnumerator to 500");
printf("Rationa l approximation to %.*f\n", DBL_DIG, value);

for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
if (0 == (int)approx) continue;
error = fabs((double)nu m / approx - value);
if (error < leasterr) {
bestnum = num;
bestdenom = approx;
leasterr = error;
printf("%8d / %-8d = %.*f with error %.*f\n",
bestnum, bestdenom,
DBL_DIG, (double)bestnum / bestdenom,
DBL_DIG, leasterr);
if (leasterr <= criterion) break;
}
}
return 0;
} /* main, ratapprx */

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Jan 6 '07 #7
CBFalconer <cb********@yah oo.comwrites:
do*********@gma il.com wrote:
>>
I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?

Try the following:

/* Find best rational approximation to a double */
If this comment is an accurate description, then I can't see how it
can help. The OP is starting with an exact, known, rational so getting
close is not the issue.

To the OP: Are you sure that simple integer arithmetic is not fast
enough? I.e.

return (valueA * valueB + 31/2) / 31;

(and I m still having trouble with 31 being the correct divisor!)

--
Ben.
Jan 6 '07 #8
"CBFalconer " <cb********@yah oo.comwrote in message
news:45******** *******@yahoo.c om...
do*********@gma il.com wrote:
>>
I'm writing a function that should do the following:

/**
* Calculate and return fraction of valueA where max fractions is 31.
* param valueA A five bit value, 0-31.
* param valueB The fraction, a five bit value, 0-31.
*
*/
ushort f ( ushort valueA, ushort valueB) {
return valueA * (valueB / 31); //the paranthesis are only here for
the looks of it.
}

I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance.
Anyone got any ideas? Table lookup?

Try the following:

/* Find best rational approximation to a double */
/* by C.B. Falconer, 2006-09-07. Released to public domain */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char **argv)
{
int num, approx, bestnum, bestdenom;
int lastnum = 500;
double error, leasterr, value, criterion, tmp;
char *eptr;

value = 4 * atan(1.0);
if (argc 2) lastnum = strtol(argv[2], NULL, 10);
if (lastnum <= 0) lastnum = 500;
if (argc 1) {
tmp = strtod(argv[1], &eptr);
if ((0.0 >= tmp) || (tmp INT_MAX) || (ERANGE == errno)) {
puts("Invalid number, using PI");
}
else value = tmp;
}
criterion = 2 * value * DBL_EPSILON;
puts("Usage: ratvalue [number [maxnumerator]]\n"
"number defaults to PI, maxnumerator to 500");
printf("Rationa l approximation to %.*f\n", DBL_DIG, value);

for (leasterr = value, num = 1; num < lastnum; num++) {
approx = (int)(num / value + 0.5);
if (0 == (int)approx) continue;
error = fabs((double)nu m / approx - value);
if (error < leasterr) {
bestnum = num;
bestdenom = approx;
leasterr = error;
printf("%8d / %-8d = %.*f with error %.*f\n",
bestnum, bestdenom,
DBL_DIG, (double)bestnum / bestdenom,
DBL_DIG, leasterr);
if (leasterr <= criterion) break;
}
}
return 0;
} /* main, ratapprx */
I believe there is an O(log N) continued fraction algorithm to do this.
Jan 6 '07 #9
"Ben Bacarisse" <be********@bsb .me.ukwrote in message
news:87******** ****@bsb.me.uk. ..
CBFalconer <cb********@yah oo.comwrites:
>>>
I'm looking for a way to get approximatly the same result by doing some
bit fiddling with the bit patterns of the values optimizing
performance .
Anyone got any ideas? Table lookup?

If this comment is an accurate description, then I can't see how it
can help. The OP is starting with an exact, known, rational so getting
close is not the issue.
What part of the OP's words "approximat ely the same result" didn't make it
by your filter?
Jan 6 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2933
by: jUrner | last post by:
Hello all I have the problem of how to calculate the resolution of the system clock. Its now two days of head sratching and still there is nothing more than these few lines on my huge white sheet of paper stiring at me. Lame I know. import time
6
19986
by: bg_ie | last post by:
Hi, I wish to write a C program which obtains the system time and hence uses this time to print out its ntp equivalent. Am I right in saying that the following is correct for the seconds part of the ntp time? long int ntp.seconds = time(NULL) + 2208988800;
0
2287
by: amarok | last post by:
Hello all. I'm a Software Engineering student, and I'm attempting to write a program in Java that does as follows: UML for the class: Fraction() Fraction(numerator: int) Fraction(numerator: int, denominator: int) Fraction(value: String) add(frac: Fraction): Fraction subtract(frac: Fraction): Fraction
6
13429
evilmonkey
by: evilmonkey | last post by:
I am very new to programming as well as Java and this is my first post so please forgive me if this is not quite posted correctly. My Problem is that I have only been using scanner to get user input into most of the exercises I have done. This exercise is asking for a user to enter two fractionslike "1/3" or "5/8". Scanner doesn't work and I don't know of another way to get this done. I think that I will have to somehow strip the "/" out and...
7
2815
by: d0ugg | last post by:
Hi, Iam writing a code for my class and I cant figure out how to solve it. I will be glad if somebody can teach me how to do something to correct it. The program is divided it 3 parts. switch (symbol) { case '+': read_frac(fraction* f); print_frac(fraction& a_fraction); answer = add(fraction f1, fraction f2); nome = "sum";
1
2214
by: d0ugg | last post by:
Hi, I'm did a fraction program for one of my programming classes and it did compile, however when I'm running the program it crashes for some reason that I do not know. // fraction.cpp #include <iostream> #include <string>
2
3019
by: d0ugg | last post by:
Hi, I'm doing a FRACTION program for one of my Programming classes and I'm getting some errors that I can't figure it out. Here is the Assignment: 1. Convert the fraction structure into a class named fraction declared in a file named fraction.h, with two private data members: an int numerator and an int denominator. 2. Convert the four arithmetic functions named add, sub, mult, and div into public member functions, each accepting a...
4
14452
by: d0ugg | last post by:
Hello everyone, I'm creating a program that it is suppose to add, subtract, multiply and also divide fractions and after that, the result has to be reduced to the lowest terms. However, I'm not sure how the algorithm of reducing fractions works. Here is part of my code: //Header File
3
3101
by: Myxamatosis | last post by:
we're given an implementation file to base our class of Fraction off of. Input and output are in the format x/y, with x and y being ints, with the "/" character in the middle. so to create an object of class Fraction, it'd need to be like Fraction frac1 (3/4) however I'm not sure on how to create this fraction with the format of the .h file we're given class Fraction
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7375
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.