0

I'm programming a microcontroller atmega168 (8 bit).

I want to do something like:

float A =  cos(- (2/3) * M_PI);

Including of course math.h (#define M_PI 3.14159265358979323846)

As result, instead of having -0.5, i get 1.

I check the result using a serial communication to my pc that i'm sure that works also for float numbers because if i set

A= -0.50;

I receive the correct result.

PS. I cannot use double...also because i don't see the reason of doing so

Help me please!

matteo
  • 3
  • 1
  • 4
    The expression `2/3` is an integer division and yields `0`, even if the whole expression is assigned to a `float`. Try `(2.0 / 3.0)`. – M Oehm Sep 17 '14 at 19:10

2 Answers2

6

2/3 is evaluated using integer arithmetic. It evaluates to 0. You mean to use floating point divide

float A = cos(-(2.0/3.0) * M_PI);

If you want float literals use an f suffix:

float A = cos(-(2.0f/3.0f) * M_PI);

Do note however, that the M_PI macro, expanded here, is a double literal. Is that what you want?

I presume the real code doesn't look quite like this. If this really is your code then you would write float A = -0.5f and move on. I guess the real code has variables.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

How much precision do you need, and where are the numbers coming from? If your goal is to compute the cosine of 120 degrees, just set a to 0.5. If your original numbers are not expressed as radians, and if you don't need an absolutely precise result, a table-based approximation may be more useful than built in trig functions, since you can strike whatever balance between table size, execution speed, and precision will best fit your needs. Note also that if your original numbers are integers, you may be able to compute trig functions without using any floating-point values [e.g. one could have a function that accepts angles from 0-65535 and returns values from -16384 to +16384]. Integer math is often much faster than floating-point, so such a function could be a major performance win.

supercat
  • 77,689
  • 9
  • 166
  • 211