|
|
View previous topic :: View next topic |
Author |
Message |
future
Joined: 14 May 2004 Posts: 330
|
Interpolation and casting problem. |
Posted: Fri Jun 18, 2004 7:46 pm |
|
|
My project needs the use of an interpolation routine..
PIC 18F452.
Code: | #include <18f452.h>
#opt 10
#zero_ram
#use rs232(baud=38400,parity=n,xmit=pin_c6,rcv=pin_c7,bits=8)
#fuses wdt,wdt128,h4,noprotect,nooscsen,nobrownout,borv20,noput,stvren,\
nodebug,nolvp,nowrt,nowrtd,nowrtb,nowrtc,nocpd,nocpb,noebtr,noebtrb
int8 linear_interp(char x1, char x2, char y1, char y2, char x) {
int16 n;
int8 x21, dx, r;
if (x<=x1) return y1; // below or equal lower bound
if (x>=x2) return y2; // above or equal upper bound
dx=x-x1; //
x21=x2-x1; // (y2-y1)*(x-x1)
// return = Y1+______________
n=y2-y1; //
n*=dx; // x2-x1
r=n/x21; //
return y1+r;
} //function call=linear_interp(22,225,0,100,101); |
If I split the operation n=(y2-y1)*dx; to the one in the formula, I get the correct results.
I Think it is a cast problem, but n=((int16 *)y2-(int16 *)y1)*(int16 *)dx gives the same wrong results.
Does anyone have a hint? |
|
|
Neutone
Joined: 08 Sep 2003 Posts: 839 Location: Houston
|
|
Posted: Fri Jun 18, 2004 10:03 pm |
|
|
If you can, pre-calculate m and b because division takes a lot of time.
Y=(m*X)+b
m=(Y2-Y1)/(X2-X1)
b=Y1-(m*X1)
Yn=(m*Xn)+b
Yn=((Y2-Y1)/(X2-X1)*Xn)+Y1-((Y2-Y1)/(X2-X1)*X1)
Yn=((Y2-Y1)/(X2-X1)*Xn)-((Y2-Y1)/(X2-X1)*X1)+Y1
Yn=((Xn-X1)*(Y2-Y1)/(X2-X1))+Y1
You can expect better casting results if you put everything on a line by it's self. It forces the compiler to perform operations in an explisit maner.
int8 linear_interp(char x1, char x2, char y1, char y2, char x) {
int8 rise,run;
int16 Y;
if (x<=x1) return y1;
if (x>=x2) return y2;
rise=y2-y1;
run=x2-x1;
Y=x-x1;
Y*=rise;
Y/=run;
return Y+Y1;
} |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|