Skip to content

Float comparisons using == cause isRunning() and other methods to behave incorrectly #44

@keldandersen412

Description

@keldandersen412

I noticed that isRunning() often returns incorrect results. The root cause appears to be comparisons like _speed == 0.0. Floating-point equality tests can produce unexpected results due to rounding errors. A safer approach is to check whether the value is smaller than a small threshold, e.g., fabs(_speed) < 0.000001.

Other methods in the library use similar comparisons, such as setSpeed(), setAcceleration(), run(), and stop(). Equality tests (== or !=) may never evaluate as expected, causing computeNewSpeed() to run unnecessarily or program logic to fail.

Any code using == or != with floats is potentially unreliable. Using comparisons like < or > is safer.

Example fix for isRunning():

bool AccelStepper::isRunning()
{
return !(fabs(_speed) < 0.000001 && _targetPos == _currentPos);
}

Affected methods (simplified summary):

void AccelStepper::setSpeed(float speed)
{
if (speed == _speed) return; // may never return
if (speed == 0.0) _stepInterval = 0; // may always evaluate false
}

void AccelStepper::setAcceleration(float acceleration)
{
if (acceleration == 0.0) return; // may never return
if (_acceleration != acceleration) computeNewSpeed(); // may always run
}

boolean AccelStepper::run()
{
return _speed != 0.0 || distanceToGo() != 0; // _speed != 0.0 may never be false
}

void AccelStepper::stop()
{
if (_speed != 0.0) move(...); // may never evaluate false
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions