Go Down

Topic: Why won't this convert properly?! It is driving me maddddd (Read 845 times) previous topic - next topic

PeterMHull

Quote
it does. That's why 4.99999999999 makes 4.


ok, but why does it return 5.00 when displaying it's double form?  It rounds for println purposes?

Quote
If you want powers of two, why are you using floating point types at all?
The processor is perfectly happy working in binary.


I'm playing with someone elses code and that's the datatype they have the class setup to accept.

WizenedEE

#6
Apr 12, 2013, 08:48 am Last Edit: Apr 12, 2013, 08:50 am by WizenedEE Reason: 1

Quote
it does. That's why 4.99999999999 makes 4.

ok, but why does it return 5.00 when displaying it's double form?  It rounds for println purposes?

Yes, the implementation of print(double) uses the same trick I showed you. From Print.cpp:
Code: [Select]

size_t Print::printFloat(double number, uint8_t digits)
{
 size_t n = 0;
 
 if (isnan(number)) return print("nan");
 if (isinf(number)) return print("inf");
 if (number > 4294967040.0) return print ("ovf");  // constant determined empirically
 if (number <-4294967040.0) return print ("ovf");  // constant determined empirically
 
 // Handle negative numbers
 if (number < 0.0)
 {
    n += print('-');
    number = -number;
 }

 // Round correctly so that print(1.999, 2) prints as "2.00"
 double rounding = 0.5;
 for (uint8_t i=0; i<digits; ++i)
   rounding /= 10.0;
 
 number += rounding;

 // Extract the integer part of the number and print it
 unsigned long int_part = (unsigned long)number;
 double remainder = number - (double)int_part;
 n += print(int_part);

 // Print the decimal point, but only if there are digits beyond
 if (digits > 0) {
   n += print(".");
 }

 // Extract digits from the remainder one at a time
 while (digits-- > 0)
 {
   remainder *= 10.0;
   int toPrint = int(remainder);
   n += print(toPrint);
   remainder -= toPrint;
 }
 
 return n;
}


if you're still curious:
http://en.wikipedia.org/wiki/Double-precision_floating-point_format

PeterMHull

Alright, I see what your saying.  I'll give that link a look tomorrow, thanks.


Fletcher Chr

Hi

Quote
BTW, what I'm trying to do basically... is count up in binary... to get this pattern:
00000001
00000011
00000111
00001111
00011111
00111111
01111111
11111111


How about this:

Code: [Select]
void setup(){
  Serial.begin(115200);
  int lines=8;
  int number=1;
 
  for (int s=lines-1;s>=0;s--){
    for (int t=lines-1;t>=0;t--){
      Serial.print(bitRead(number,t));
    }
    Serial.println();
    number<<=1;  // bitshift number one to the left
    number+=1;   // add 1 to the right most bit
  }
}

void loop(){}


Output:
00000001
00000011
00000111
00001111
00011111
00111111
01111111
11111111


-Fletcher

Go Up