# Need an equation

Discussion in 'Math' started by Jassper, Jun 6, 2009.

1. ### Jassper Thread Starter Active Member

Sep 24, 2008
84
1
I hope this makes sence,
I have an incomeing value anywhere from 0 to 65535. This represents 0 to 100%, 0 value being 0% and 65535 value being 100%. I need an equation that will take the incoming value and spit out a value that will be in 5% steps.

i.e
0% - 5% - 10% - 15% - etc
The actual output being, (rounded up)
0 - 3277 - 6553 - 9830 - etc

Or must I do
integer i = (Value_IN \ 3277) * 5;
if(i < 5)
i_Out = 0;
else if(i > 4 && < 10)
i_Out = 3277%;

etc

I would rather not do a string of if, else if unless I have to.

THANKS

2. ### hgmjr Retired Moderator

Jan 28, 2005
9,030
218
Since there are only 21 values (if you include zero), this may be a good place for a lookup table. Create an array of 21 elements and put in the actual binary or hexadecimal values that represent the 5% steps. You can then search the array with a binary search to find the value you need.

Or you could create a do-loop that starts with 0 and increments by 5% of the fullscale until the value exceeds the value and then choose the 5% value that is closest to the input 16-bit value.

hgmjr

3. ### Mark44 Well-Known Member

Nov 26, 2007
626
1
You sort of have the idea, but your code definitely needs help. Clearly you need to break up the range of input values (0 to 65535) in chunks of length 3277. Since your output values are going to be 0%, 5%, 10%, and so on, you are going to have to decide when your output value jumps to the next level.

One possibility is at the middle of the interval.

input: 0 to 1637
output: 0

input: 1637 to 4914
output: 5

And so on. You might want to recheck the boundary points I used.

If you do it that way, you can have a sequence of if statements, like so:
Code ( (Unknown Language)):
1.
2. // get an input value, in_value
3.
4. int out_value;
5.
6. if (in_value >= 0 && in_value <= 1637)
7.    out_value = 0;
8. else if (in_value > 1637 && in_value <= 3277)
9.    out_value = 5;
10. // and so on for all 20 intervals
11.
I'm doing this in C/C++. That's sort of what your code looked like.

I'm sure someone could write the code that would do the same calculation all in one assignment statement, but I don't want to have to think about it that hard. Besides, clever code often doesn't run any faster, and is harder to understand and maintain.

Hope that helps.

4. ### Jassper Thread Starter Active Member

Sep 24, 2008
84
1
Thanks, I'm not a good enough programmer to do a look up table, but the do loop sounds plausible.

Thanks for the help.