??? 03/10/09 15:13 Modified: 03/10/09 15:14 Read: times |
#163303 - Bisection. Responding to: ???'s previous message |
Anyone have some advise for a seemly easy problem?<p>
With as little as four comparison operations, you can find out how many bars to light. The process works by dividing the range of bar in half with each comparison, i.e. with the first comparison, you check whether you need to light more than seven bars or not, etc. This approach is most likely faster than using a divison on a '51, but will result in four levels of nesting, which may or may not agree with your sense of aesthetics. :) Alternatively, if you want to go the division route: Bar_Value = (0x0E / (0x8C/SpeedCalculated)); // 140 used for testing you may want to use a higher precision than 8 bits, at least in the intermediate steps, and apply rounding to minimize the worst case error. E.g. #define NUMBER_OF_BARS 14 #define MAXIMUM_SPEED_IN_MPH 140 #define SCALE_EXPONENT 5 unsigned short tmp; unsigned char bar_value; tmp = (unsigned short) NUMBER_OF_BARS * speed_in_mph; /* maximum: 14 * 140 = 1960 */ tmp = (tmp << SCALE_EXPONENT); /* use all 16 availaable bits, maximum: 1960 * 32 = 62720 */ tmp = tmp / MAXIMUM_SPEED_IN_MPH; tmp = (tmp + (1 << (SCALE_EXPONENT - 1))) >> SCALE_EXPONENT; */ Round /* bar_value = (unsigned char) tmp; |