Exponential math in script

For reading a volumetric water content sensor I’m trying to let HA handle the following equation:

The hardest part was already done by a fellow HA user and shared this config:

// for soilless media using calibration equation
// float VWC = ((6.771 * pow(10, -10) * pow(mySensor.sensorTEROS12.calibratedCountsVWC, 3))
// - (5.105 * pow(10, -6) * pow(mySensor.sensorTEROS12.calibratedCountsVWC, 2))
// + (1.302 * pow(10, -2) * mySensor.sensorTEROS12.calibratedCountsVWC))
// - 10.848;

However, I can’t figure out where to put this configuration (scripts?) and what it takes as sensor input (integer or string). My VWC sensor is configured with entity_id: sensor.vwc_s1. That sensor reads a string like ‘2914.01’ in its state.

It would go in a state based template sensor:

And for more on how to construct a template:

You will find you need to cast your sensor state as a floating point number, like this:

{{ states('sensor.vwc_s1')|float }}

This tool is available to test your templates:

Open your Home Assistant instance and show your template developer tools.

Problem is that neither jinja2 nor HA support pow :wink:
Nevermind, not actually really needed if you don’t mess with the number of zeroes :slight_smile:

jinja has x**y which is x to the power y.

so 5.105 * pow(10, -6) would be 5.105 * 10 **-6


Yep, just found out :+1:

But yeah, at the end of the day 5.105 / 1000000 is not that bad :wink:
PS: or 0.000005105, as most as constants.

6.771 x 10-10 can be expressed as 6.771e-10


Thanks guys, I’l be going to play around with this

Thanks again for helping me out on this. For the guys that like to copy like me, the working template:


  - platform: template
        friendly_name: Calculated Volumetric Water Content Sensor 1
        unit_of_measurement: "θ"
        value_template: >
          {{ ((6.771e-10) * (states('sensor.vwc_s1')|float ** 3) -
             (5.105e-6) * (states('sensor.vwc_s1')|float ** 2) +
             (1.302e-2) * (states('sensor.vwc_s1')|float) -10.848) | round(3)  }}

As Taras mentionned, this can be expressed as 6.771e-10, which is both more efficient and more readable :wink:

1 Like