Clear Filters
Clear Filters

Base-4 arithmetic in MATLAB

1 view (last 30 days)
Paul Huter
Paul Huter on 29 Jul 2017
Edited: John D'Errico on 30 Jul 2017
Does code already exist for doing Base-4 arithmetic in MATLAB? I find myself needing to average several numbers that are in Base-4, and I am unsure of exactly how to go about doing this. I have seen things like "convert to Base-10, do the math, then convert back", but this really only works if the result of the average is an integer. The thought has occured to me to simply truncate the resulting average (round down), and then convert that back to Base-4, but that seems like I may be inadvertently producing an erroneous average.
I would like to take my Base-4 numbers, add them all up, divide by the number of numbers, and get a resulting Base-4 answer - if this is possible.
Thoughts, suggestions?
  2 Comments
James Tursa
James Tursa on 29 Jul 2017
Why does converting to IEEE double numbers, doing the math, and then converting back not work for you? The average value is the same underlying number, regardless of base and regardless of whether the result is an integer or not. Why do you seem to think otherwise? Can you give a counterexample where this doesn't give the answer you think it should?
John D'Errico
John D'Errico on 29 Jul 2017
The average of two numbers is not dependent on what base they are represented in. Why does it matter if the result is not an integer?

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 30 Jul 2017
Edited: John D'Errico on 30 Jul 2017
The average of two numbers is not dependent on what base they are represented in. Why does it matter if the result is not an integer?
If you will only accept an integer result, note that ANY integer is representable in base 4 as well as base 10. If a number is not an integer in base 10, then it is also not an integer in base 4 either. So converting to base 10 to do the arithmetic, then converting back to base 4 must be sufficient. You can freely truncate the base 10 result to an integer, or round it as you choose, before the reconversion to your chosen base.
Of course, yes, you CAN do the computations in base 4. This is not that difficult. But it is also not even remotely necessary. Or you could compute a fractional result in base 4. Again, not that difficult.
But nothing at all stops you from doing the arithmetic in any base you choose. A number base is merely a representation of an integer. It does not change that number in any significant way. (Ok, if we are talking about fractions, then one can argue that 1/3, as represented in base3 is exactly representable, whereas it is not representable exactly in base 10, or base 2, for that matter. But you seem to be asking about integer representations.)

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!