ROBOTC.net forums
http://robotc.net/forums/

Robot 2.26 Possible Compiler Error
http://robotc.net/forums/viewtopic.php?f=11&t=2649
Page 1 of 1

Author:  vamfun [ Fri Oct 15, 2010 2:05 am ]
Post subject:  Robot 2.26 Possible Compiler Error

//test program for multiplication of floats and integer precedence


Ran this simple program

Code:
task main()
{

  int error = 100;
  float kp = .1;

 int ans1 = kp*error;           // this gives 10
 int ans2 = -kp*error;          // this gives 0   seems to be an error
 int ans3 = -kp*(float)error; // this gives -10
 int ans4 = -.1*error;          // this gives -10
 
}


It appears that for ans2 when the sign of kp*error is changed, the compiler treats kp as an integer rather than a float as in all the other cases.

Any ideas why?

Author:  mightor [ Fri Oct 15, 2010 3:41 am ]
Post subject:  Re: Robot 2.26 Possible Compiler Error

Could you send a bug report to suppor@robotc.net with this piece of code and a short description of the problem?

Thanks,
Xander

Author:  Dick Swan [ Fri Oct 15, 2010 9:19 pm ]
Post subject:  Re: Robot 2.26 Possible Compiler Error

vamfun wrote:
Any ideas why?

Yes. I confirmed this is a compiler bug. Looks like it might have been there day one. In some cases the compiler has got to "fancy" in trying to eliminate temporary variables in calculations.

It goes something like this:
<int A> = <factor B> * <factor C>

If either "B" or "C" is a float expression then compiler should do the "times" at float precision using a temporary variable and then convert the temporary variable back to an integer.

In a few weird cases, due to a missing case statement in the bowels of the compiler, compiler incorrectly thinks it can eliminate the temporary variable and instead generate the code for
<int A> = B;
<int A> *= C;
which is incorrect because "B" was a float value that should be preserved.

I have fixed the bug. It should be in version 2.31.

Sorry about that.

Workarounds for this example include:

declaring 'kp' as c'const'.

moving the unary '-' outside the expression -(kp*error)
doing all the calculations at float precsions; eg. "float ans2".

Author:  mightor [ Sat Oct 16, 2010 1:56 am ]
Post subject:  Re: Robot 2.26 Possible Compiler Error

You can also use casting to get the correct behaviour:

Code:
task main()
{
  int error = 100;
  float kp = .1;
 
  int ans1 = (float)kp*error;
  int ans2 = (float)-kp*error;
  int ans3 = (float)-kp*(float)error;
  int ans4 = (float)-.1*error;
}


This works the same as this:
Code:
task main()
{
  int error = 100;
  float kp = .1;
 
  int ans1 = (float)(kp*error);
  int ans2 = (float)(-kp*error);
  int ans3 = (float)(-kp*error);
  int ans4 = (float)(-.1*error);
}


- Xander

Page 1 of 1 All times are UTC - 5 hours [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/