View unanswered posts | View active topics It is currently Mon Apr 21, 2014 8:10 am






Reply to topic  [ 3 posts ] 
How to calculate with precision on PIC 
Author Message
Rookie

Joined: Sat Apr 13, 2013 10:37 pm
Posts: 8
Post How to calculate with precision on PIC
So, say I have a calculation I want to run on my PIC:
Code:
int a = 33;
float b = 18.888889;
int c = (int)(a * b);


How would I go about doing this?
PIC doesn't allow floats or for integer values to go over 32,767.

If I want, say, two-decimal precision, I would do this:
Code:
int a = 33;
int b = 1889;
int c = (a * b) / 100;


But, then the integer value overflows.

Does anyone have a workaround? I only want two decimals.


Sun Apr 14, 2013 6:26 pm
Profile
Moderator
Moderator
User avatar

Joined: Wed Mar 05, 2008 8:14 am
Posts: 3108
Location: Rotterdam, The Netherlands
Post Re: How to calculate with precision on PIC
There is no way to calculate with precision on the PIC, but you could do some of the work at compile time. If you have something like
Code:
int time = degrees * 15000 / 90;

Why not change that to
Code:
int time = degrees * 167;

You will always lose precision when you're on a platform without floats and longs, it's a limitation that you have to accept and work around. Sometimes you can do this by doing something like:
Code:
int a = 33;
int b = 19;  // you're off by 0.5%
int c = (a * b) ;

If that's good enough for you, then you've saved yourself a heap of trouble.

= Xander

_________________
| Professional Conduit of Reasonableness
| (Title bestowed upon on the 8th day of November, 2013)
| My Blog: I'd Rather Be Building Robots
| ROBOTC 3rd Party Driver Suite: [Project Page]


Mon Apr 15, 2013 12:47 am
Profile WWW
Rookie

Joined: Sat Apr 13, 2013 10:37 pm
Posts: 8
Post Re: How to calculate with precision on PIC
Thanks, I guess I'll have to upgrade one of these days. :|


Mon Apr 15, 2013 12:58 am
Profile
Display posts from previous:  Sort by  
Reply to topic   [ 3 posts ] 

Who is online

Users browsing this forum: No registered users and 1 guest


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 post attachments in this forum

Search for:
Jump to:  



Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software for PTF.