Data Types in Arduino

Pages

Contributors: b_e_n

Testing Data Types (Multiplication/Division)

Now let’s look at what happens with ‘harder’ math - multiplication and division.

Here are some screen grabs for multiplication:

Multiply with bytes screen capture[(https://dlnmh9ip6v2uc.cloudfront.net/tutorialimages/datatypes/mult_int.jpg)

Multiply with bytes screen capture[(https://dlnmh9ip6v2uc.cloudfront.net/tutorialimages/datatypes/mult_float.jpg)

Check out the elapsed times: 4µs for byte, 8 for int or long, and 12 for float - longer for larger data types, and also what we expect to see in terms of ‘harder’ math taking longer. Multiplication is still hardware supported, though - there is a native multiply instruction in the processor which makes multiply operations relatively easy. But what about division?

Divide with bytes screen captureDivide with ints screen capture

Divide with longs screen captureDivide with floats screen capture

Oh, my. byte division isn’t too bad at 16µs, but 48 for long? Ouch. The problem here is that division does NOT have a native instruction in the Atmega instruction set, so the compiler has to do some back flips to create one. So, final lesson: not all mathematical operations are created equal. Divide takes a lot longer than multiply or add (or subtract, but that’s really just add with a minus sign), and something like finding a square root or a sine would take even longer. So long, in fact, that it’s often easier just to maintain a list of values for square roots or sine/cosine/tangent and look up the value that you want than it is to calculate it.


Want more information about SparkFun's classes? Interested in getting involved with teaching electronics? Just want to talk? Sign up for our newsletter, or contact our education department.

SparkFun is a company built around one core idea – sharing ingenuity. We think everyone should have the hardware and resources to learn and play with cool electronic gadgetry.

Share, give, learn, SparkFun.

Do you regularly instruct classes and workshops in a formal or informal learning environment? SparkFun offers Educator Discounts to people teaching and sharing electronics.

Find out more.