Skip to content

Commit

Permalink
Workaround Fan PercentSetting floating point precision error after "c…
Browse files Browse the repository at this point in the history
…eil()" (#27912)

* Workaround Fan Percent Setting floating point err

Workaround floating point precision error which will cause invalid value
after ceil()

For example, the current value:
   speedMax: 10
   percent: 70
   speedMax * (percent * 0.01) = 7.000000000000001 (floating point
precision error)
   ceil(speedMax * (percent * 0.01)) = 8 => The error propagate to ceil
and cause the final result error.

* Restyled by clang-format

* Workaround Fan PercentSetting float error (2nd)

Use integer multiply & devide to workaround floating
point precision error which causes incorrect Fan PercentSetting
value after ceil calculation.

* Update src/app/clusters/fan-control-server/fan-control-server.cpp

Co-authored-by: Boris Zbarsky <[email protected]>

---------

Co-authored-by: Restyled.io <[email protected]>
Co-authored-by: Andrei Litvin <[email protected]>
Co-authored-by: Boris Zbarsky <[email protected]>
  • Loading branch information
4 people authored and pull[bot] committed Jan 10, 2024
1 parent 7637fec commit e6d5ae9
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/app/clusters/fan-control-server/fan-control-server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,9 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt
VerifyOrReturn(EMBER_ZCL_STATUS_SUCCESS == status,
ChipLogError(Zcl, "Failed to get SpeedSetting with error: 0x%02x", status));

float percent = percentSetting.Value();
uint8_t speedSetting = static_cast<uint8_t>(ceil(speedMax * (percent * 0.01)));
uint16_t percent = percentSetting.Value();
// Plus 99 then integer divide by 100 instead of multiplying 0.01 to avoid floating point precision error
uint8_t speedSetting = static_cast<uint8_t>((speedMax * percent + 99) / 100);

if (currentSpeedSetting.IsNull() || speedSetting != currentSpeedSetting.Value())
{
Expand Down

0 comments on commit e6d5ae9

Please sign in to comment.