From cd57469e06aaf223c518c72b17c07e80722982fc Mon Sep 17 00:00:00 2001 From: jerome992 <35580081+jerome992@users.noreply.github.com> Date: Mon, 20 Mar 2023 05:22:22 +0100 Subject: [PATCH] Fix negative sqrt root in ct_clamp_sensor.cpp (#2701) (#4236) Co-authored-by: Jerome --- esphome/components/ct_clamp/ct_clamp_sensor.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/esphome/components/ct_clamp/ct_clamp_sensor.cpp b/esphome/components/ct_clamp/ct_clamp_sensor.cpp index 51b0f1318c..d555befcde 100644 --- a/esphome/components/ct_clamp/ct_clamp_sensor.cpp +++ b/esphome/components/ct_clamp/ct_clamp_sensor.cpp @@ -33,7 +33,10 @@ void CTClampSensor::update() { const float rms_ac_dc_squared = this->sample_squared_sum_ / this->num_samples_; const float rms_dc = this->sample_sum_ / this->num_samples_; - const float rms_ac = std::sqrt(rms_ac_dc_squared - rms_dc * rms_dc); + const float rms_ac_squared = rms_ac_dc_squared - rms_dc * rms_dc; + float rms_ac = 0; + if (rms_ac_squared > 0) + rms_ac = std::sqrt(rms_ac_squared); ESP_LOGD(TAG, "'%s' - Raw AC Value: %.3fA after %d different samples (%d SPS)", this->name_.c_str(), rms_ac, this->num_samples_, 1000 * this->num_samples_ / this->sample_duration_); this->publish_state(rms_ac);