Solution for bug in trig routines with large angles

General discussion relating to the library modules supplied with the compiler

Moderators: David Barker, Jerry Messina

Post Reply
matherp
Registered User
Registered User
Posts: 31
Joined: Tue May 31, 2011 2:59 pm
Location: Cambridge

Solution for bug in trig routines with large angles

Post by matherp » Mon Jun 20, 2011 9:34 am

There is a bug in the cos routine (and therefore also sine) when the angle in radians is too large. This is demonstrated in the attached test program

Code: Select all

{
****************************************************************
*  Name    : I2C EEPROM                                        *
*  Author  : David John Barker                                 *
*  Notice  : Copyright (c) 2006 Mecanique                      *
*          : All Rights Reserved                               *
*  Date    : 04/04/2006                                        *
*  Version : 1.0                                               *
*  Notes   :                                                   *
*          :                                                   *
****************************************************************
}

// if device and clock are omitted, then the compiler defaults to 
// 18F452 @ 20MHz - they are just used here for clarity...
Device = 18F4520
Clock = 20

// import libraries...
Include "utils.bas"
Include "math.bas"
Include "USART.bas"
Include "convert.bas"


// program start...


// program start...
SetAllDigital()
DelayMS(10)
USART.SetBaudrate(br19200)
USART.Write(FloatToStr(cos(500)),13,10)
USART.Write(FloatToStr(cos(fmod(500,2*pi))),13,10)
usart.write(13,10)
which gives the output
-2147483647.647
-0.883

The solution is to add the line:
pvalue=fmod(pvalue, twopi)

to the cos routine and define twopi in the module constants
const twopi = 6.28318530717959

This also solves the problem for sine. I haven't checked tan but the fix would obviously work for that as well

Best regards

peter

Post Reply