This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Compiler/TMS320F28335: Operations floating point

Part Number: TMS320F28335

Tool/software: TI C/C++ Compiler

Hello,

I am having problems with operation results. The operations involve are multiplications and divisions. The result seems to be correct if you watch it in expressions window but it is not if you cast the value and you check memory browser.

I have simplified the operations only to show the problem.

int c = 66, d = 800;

float a;

a=(c/1.1)*(d/d);

The result as appears in expressions window is 60, but in memory browser is 0x426FFFFF which is 59.999999.

I guess that this is because the floating point but if I use the numbers directly the result is correct.

How should I do the operations?

Thank you,

Paloma

  • Paloma,

    You are correct. The error is an artefact of finite resolution in 32-bit floating-point. It happens because the different exponents in 66 and 1.1 when you do the division (FPU32 uses IEEE745 floating point format in which bits 30-32 define the exponent).

    If you hard code the numbers into the code the compiler is helping you out by doing the calculation for you at build time and just loading the result directly to memory. You can see this in the generated assembly below:

    a=(66/1.1)*(800/800);
    00a602: E8021380 MOVIZ R0, #0x4270
    00a604: E203000A MOV32 @0xa, R0H

    Also, if I declare:

    float x1 = 66/1.1;
    float x2 = 800/800;

    I get:

    a = x1*x2;
    00a606: E2AF0006 MOV32 R0H, @0x6, UNCF
    00a608: E2AF0108 MOV32 R1H, @0x8, UNCF
    00a60a: E7000008 MPYF32 R0H, R1H, R0H
    00a60c: 7700 NOP
    00a60d: E203000A MOV32 @0xa, R0H

    In both cases the registers are being loaded with the compiler calculated results without the FPU doing anything. You are doing the calculation correctly. The error is unavoidable with 32-bit floating point.

    Regards,

    Richard
  • Do you think that it is a good idea to add +0.5 to the ‘a’ to round it? I want to generalize the result, not only to obtain 60.

    Thank you very much.

    Paloma
  • Paloma,

    No, I don't think that would be reliable. What you can do is use roundf(), something like this:
    a = roundf( (float) (c/1.1)*(d/d));

    roundf() takes about 130 cycles, so you'll have to keep that in mind if you use it a lot.

    Regards,

    Richard