double type?

Status
Not open for further replies.

so999

Member
Hello,
I have problems to understand what is happening in a simple test on teensy 3.2 board.
I simply multiplied 4 double constants and the result is not what I expected.

Code:
const double beltRatio = 10.0;
const double frictionRatio = 35.8;
const double stepsNumber = 1000.0;
const double microSteps = 80.0; 
double totalMicrostepsNumber = 0.0;

void setup() {
totalMicrostepsNumber=stepsNumber * microSteps * beltRatio * frictionRatio;
}

void loop() {
Serial.println(totalMicrostepsNumber);
delay(1000);
}

The printed result in monitor is 28639999.39 instead of 28640000
Could you help me to understand what is wrong with my code?
 
It's not your code, but a setting used for the benefit of 32 bit FPU usage. Constants default to only 32 bits on Teensy 3.x, even if they're assigned to 64 bit double. That's a huge benefit for people using the FPU and code written for 8 bit Arduino, which has only 32 bit floats even for double.

But if you really want to use 64 bits with constants, you need to use this:

Code:
const double beltRatio = 10.0L;
const double frictionRatio = 35.8L;
const double stepsNumber = 1000.0L;
const double microSteps = 80.0L; 
double totalMicrostepsNumber = 0.0L;

Serial.println() also truncates to only 32 bit precision, which isn't an issue in this case, but another thing to keep in mind as you're working with 64 bit double.
 
But if you really want to use 64 bits with constants, you need to use this:

Thank you Paul.
I used constants because they are fixed parameters. But it is not mandatory. However even if I declare them without “constant”:
double frictionRatio = 35.8; etc the result is also truncated.
Is the “double” type of 32bit (without “L” suffix)?
 
Yes, double is 64 bit.

But a number like "35.8" in your code is only 32 bits precision, unless you add the "L" or "LL" suffix. Without the suffix, a 32 bit number is being put into your 64 bit double, leaving many of the bits as zeros.

This is non-standard behavior, enabled by gcc's "-fsingle-precision-constant" option. Normally such numbers would be 64 bits. Normally, if you use those numbers in equations or other code, they automatically promote the results to 64 bits.

On Teensy, we use "-fsingle-precision-constant" to avoid such common usage causing almost everything to become much slower 64 bit double precision math. With Teensy 3.5 & 3.6, the FPU does 32 bit float very fast in hardware, but 64 bit double is slow in software. Even on Teensy LC & 3.2 where both are software, 32 bits is much faster.

So on Teensy, if you want 64 bit numbers in your code, you need to add that suffix.
 
Status
Not open for further replies.
Back
Top