ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

ZeroDivisionError: float division by zero

asked 2021-01-07 06:51:18 -0600

Redhwan gravatar image

How to fix this issue. I followed this video here

This full code:

#!/usr/bin/env python
import rospy

from std_msgs.msg import String

rate1 = 30
rate2 = 1
msg1 = "30 hz"
msg2 = "1 hz"

def callbsck1(event):

def callbsck2(event):

if __name__ == '__main__':
  pub_1 = rospy.Publisher ('topic1', String, queue_size=10)
  pub_2 = rospy.Publisher('topic2', String, queue_size=10)
  rospy.Timer(rospy.Duration(1/rate1), callbsck1)
  rospy.Timer(rospy.Duration(1 / rate2), callbsck2)

This error:

Exception in thread Thread-5:
Traceback (most recent call last):
  File "/usr/lib/python2.7/", line 801, in __bootstrap_inner
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/", line 221, in run
    r = Rate(1.0 / self._period.to_sec(), reset=self._reset)
ZeroDivisionError: float division by zero
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-01-07 07:05:23 -0600

mgruhler gravatar image

updated 2021-01-07 07:06:15 -0600

Python 2 treats the division operator / differently, depending on the operands. If both operands are integers (this is what you have here with 1 and 30) it is an integer division (and float division, if one of the operands is a float).

Integer division only returns the "integer" part, the fractional part is discarded. Thus, you'll end up with 1/30=0.

(In Python 3, / is always float division. // is integer division)

There are multiple ways to fix this:

  1. make at least one of the operands a float by adding a dot, i.e. 1.0, 30.0 or even 1. or 30.
  2. cast one of the operands explicitly to float: float(1), float(30)
  3. "activate" the Python 3 behavior of having / always as float division using a future import

    from __future__ import division

    (Note that __future__ imports have to come before any other import statement)

edit flag offensive delete link more


Thanks, it is fine now

Redhwan gravatar image Redhwan  ( 2021-01-07 07:17:27 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2021-01-07 06:51:18 -0600

Seen: 5,575 times

Last updated: Jan 07 '21