Error while processing template ... ZeroDivisionError: float division by zero

Hi there,

since a few weeks I have a problem I can’t get rid of… I searched a lot in the forum (you can find many things to “float division by zero”), but I could not solve my problem. I now have a template that is the most compact I could create for my needs and to make it easy to you to understand (I hope so…)

sensor.yaml

strom_eigenverbrauchsanteil: # Ratio in Percent = Home Consumption / Home Production(Solar, Battery)*100
  friendly_name: "Eigenverbrauchsanteil"
  unit_of_measurement: "%"
  value_template: >-
    {% set ratio = ((100/((states('sensor.PV_ACPowerValue') | float(0) + states('sensor.varta_entladung_only') | float(0)) / (states('sensor.varta_beladung_only') | float(0.001) + states('sensor.strom_aktueller_verbrauch') | float(0.001) + 0.001))) | float(0) | round(0)) %}
    {% if ratio > 100 %}
      {{ 100 }}
    {% elif ratio < 0 %}
      {{ 0 }}
    {% elif ((ratio >= 0) and (ratio <= 100)) %}
      {{ ratio }}
    {% else %}
      {{ 0 }}
    {% endif %}

home-assistant.log

2022-05-06 11:19:09 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{% set autarky = ((states('sensor.PV_ACPowerValue') | float(0) + (states('sensor.varta_aktuelle_leistung_kw') | float(0)) * -1) * 100 / (states('sensor.strom_aktueller_verbrauch') | float(0.001) + states('sensor.strom_einspeisung') | float(0.001))) | float(0) | round(0) %} {% if autarky > 100 %}
  {{ 100 }}
{% elif autarky < 0 %}
  {{ 0 }}
{% elif ((autarky >= 0) and (autarky <= 100)) %}
  {{ autarky }}
{% else %}
  {{ 0 }}
{% endif %}")
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 409, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1859, in _render_with_context
    return template.render(**kwargs)
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 1291, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 926, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
ZeroDivisionError: float division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 525, in async_render_to_info
    render_info._result = self.async_render(variables, strict=strict, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 411, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: ZeroDivisionError: float division by zero
2022-05-06 11:19:09 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('ZeroDivisionError: float division by zero') while processing template 'Template("{% set autarky = ((states('sensor.PV_ACPowerValue') | float(0) + (states('sensor.varta_aktuelle_leistung_kw') | float(0)) * -1) * 100 / (states('sensor.strom_aktueller_verbrauch') | float(0.001) + states('sensor.strom_einspeisung') | float(0.001) + 0.001)) | float(0) | round(0) %} {% if autarky > 100 %}
  {{ 100 }}
{% elif autarky < 0 %}
  {{ 0 }}
{% elif ((autarky >= 0) and (autarky <= 100)) %}
  {{ autarky }}
{% else %}
  {{ 0 }}
{% endif %}")' for attribute '_attr_native_value' in entity 'sensor.strom_autarky'

the 0.001 ist just added to avoid “float division by zero”. I don’t get why it is still possible that my calculation tries to divide by zero. I think catch every error.

The error appears after I restart my Home-Assistant.

Home Assistant Core 2022.5.1
Home Assistant Supervisor 2022.05.0
Home Assistant OS 7.4
Kernel version 5.10.98
Agent version 1.2.1

thanks i advance!

The ratio is

(
	(100/(
			(states('sensor.PV_ACPowerValue') | float(0) + states('sensor.varta_entladung_only') | float(0))
			/ (states('sensor.varta_beladung_only') | float(0.001) + states('sensor.strom_aktueller_verbrauch') | float(0.001) + 0.001)
		)
	)
	| float(0) | round(0)
)

So if (states('sensor.PV_ACPowerValue') | float(0) + states('sensor.varta_entladung_only') | float(0)) equals zero, you have the error

Even if both of them are zero I don’t divide by 0.

100/(0/0.001+0.001) = 100000

I just added the static 0.001 to avoid that problem, or do I have another logical problem.

You’re doing
0/(0.001+0.001+0.001) = 0

(100/(0/(0.001+0.001+0.001)) = division by zero

1 Like

:man_facepalming:

thanks man

I think I’m just bad at maths, but I don’t get it. Why do I get this error even after adjusting my calculation…


    strom_eigenverbrauchsanteil: # Ratio in Percent = Home Consumption / Home Production(Solar, Battery)*100
      friendly_name: "Eigenverbrauchsanteil"
      unit_of_measurement: "%"
      value_template: >-
        {% set ratio = ((100/((states('sensor.PV_ACPowerValue') | float(0) + states('sensor.varta_entladung_only') | float(0)) / (states('sensor.varta_beladung_only') | float(0.001) + states('sensor.strom_aktueller_verbrauch') | float(0.001)) + 0.001)) | round(0)) %}
        {% if ratio > 100 %}
          {{ 100 }}
        {% elif ratio < 0 %}
          {{ 0 }}
        {% elif ((ratio >= 0) and (ratio <= 100)) %}
          {{ ratio }}
        {% else %}
          {{ 0 }}
        {% endif %}

image

This is my calculation… Where do I divide by zero?

The super class of ZeroDivisionError is ArithmeticError. This exception raised when the second argument of a division or modulo operation is zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws “ZeroDivisionError” error if the result is infinite number. While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate.

try:

    z = x / y
except ZeroDivisionError:
    z = 0

Or check before you do the division:

if y == 0:
    z = 0
else:
    z = x / y

The latter can be reduced to:

z = 0 if y == 0 else (x / y)

1 Like