Pages: [1]   Go Down
Author Topic: Arduino calculating math incorrectly?  (Read 523 times)
0 Members and 1 Guest are viewing this topic.
Brampton, Ontario
Offline Offline
Full Member
***
Karma: 0
Posts: 112
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Serial.println(LightValue);
Serial.println(LightValue/770*255);
>552
>0

while it should be
>552
>182.805

Why is this occurring?
Logged

California
Offline Offline
Faraday Member
**
Karma: 82
Posts: 3123
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Serial.println(LightValue);
Serial.println(LightValue/770*255);
>552
>0

while it should be
>552
>182.805

Why is this occurring?
That is correct.

The problem is you are expecting floating point math, but telling the compiler that you want integer math:
Code:
Serial.println(LightValue);
Serial.println(LightValue/770.0*255.0);
Logged

Brampton, Ontario
Offline Offline
Full Member
***
Karma: 0
Posts: 112
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Tried making it a double to see if it would work, would have made sense to make it a float.

Thanks!
Logged

New Jersey
Offline Offline
Faraday Member
**
Karma: 50
Posts: 3429
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Float and double are the same size for the Arduino
Logged

Brampton, Ontario
Offline Offline
Full Member
***
Karma: 0
Posts: 112
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Really? Hm. What's the point in having both then?
Logged

Sydney, Australia
Offline Offline
Edison Member
*
Karma: 27
Posts: 1186
Big things come in large packages
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
for the Arduino

That is not the case for other implementations of C/C++. The bigger the precision the more it takes to calculate, especially as there is no floating point hardware support. How many decimal places to you need?
« Last Edit: July 23, 2012, 08:07:11 pm by marco_c » Logged

Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Brampton, Ontario
Offline Offline
Full Member
***
Karma: 0
Posts: 112
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

"That is not the case for other implementations of C/C++."
I know. But, since arduino's float counts as double and double counts as float, why have both?
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 178
Posts: 12288
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


Because the C++ standard requires both types.
Logged

California
Offline Offline
Faraday Member
**
Karma: 82
Posts: 3123
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

"That is not the case for other implementations of C/C++."
I know. But, since arduino's float counts as double and double counts as float, why have both?
Portability.
Logged

Pages: [1]   Go Up
Jump to: