Задача — построить график функции sin(2*3.14*i/50)/cos(2*3.14*i/50)
на Python
while i<=50:
y=math.sin(2*3.14*i/50)/math.cos(2*3.14*i/50)
if(y>max):
max=y
elif(y<min):
min=y
i+=1
print('n')
j=1
while j<=50:
y= math.ceil(((math.sin(2*3.14*i/50)/math.cos(2*3.14*i/50))-min)*50/(max-min))
if y==50-j:
print('*')
else:
print (' ')
j+=1
print(max)
print(min)
При запуске выходит ошибка:
ZeroDivisionError: float division by zero.
Проверял — значения максимума и минимума присваиваются верно, значит беда во внутреннем цикле. Зафэйлил с пробелами, или же в Python так вообще делать нельзя?
Обновление
Изначально:
import math
min=max=math.sin(2*3.14/50)/math.cos(2*3.14/50)
i=1
Значения max = 15.7029740933...
, min = -16.53312943...
. Отсчет i
начинается с 1, изначально max = min
, а затем присваиваем значения.
Вывел min
и max
перед ошибкой. Оба значения 0.126264… Хотя если убрать внутренний цикл — все нормально. По идее должно 50 раз вывести на экран значения max
и min
(15.703… и -16.533).
задан 25 окт 2015 в 16:19
10
Если min=max
хотя бы на одной (первой) итерации цикла, то это достаточно чтобы ошибка деления на ноль (ZeroDivisionError
) возникла, что прерывает нормальное исполнение кода.
Чтобы лучше понять что происходит, попробуйте выбросить весь код и оставьте только min
:
min = 0
while True:
1 / min # выбрасывается ошибка на первой итерации
min += 1
В этом коде min=0
только на одной (первой) итерации цикла, но этого достаточно чтобы ошибка деления на ноль завершила программу (дальнейшие итерации не состоятся). Eсли min=1
в начале поставить вместо min=0
, то это создаст бесконечный цикл с разными значениями min
на каждой итерации.
ответ дан 26 окт 2015 в 12:59
jfsjfs
51.9k11 золотых знаков107 серебряных знаков309 бронзовых знаков
Для подобной задачи обычно используют такой подход:
- Первым делом считаются точки по которым строится график (тут же можно посчитать максимум и минимум)
- По точкам строим график
А для циклов в питоне лучше использовать for. Так код легче читается и в таком цикле сложнее сделать ошибку. while в питоне достаточно редкий гость.
Если сложить все вместе, то получится примерно такой код:
import math
max_y=min_y=None
ys=[]
for i in range(1,51):
y=math.sin(2*3.14*i/50)/math.cos(2*3.14*i/50)
max_y = max(y, max_y) if max_y is not None else y
min_y = min(y, max_y) if min_y is not None else y
ys.append(y)
spaces = ' '*50
for y in ys:
i = math.ceil((max_y - y)*50/(max_y - min_y))
print(i)
print(spaces[:i] + '*' + spaces[i+1:])
ответ дан 2 ноя 2015 в 19:36
Если задача нарисовать звездочками график,
у меня получился такой код:
import math
min=max=math.sin(2*3.14/50)/math.cos(2*3.14/50)
i=1
while i<=50:
y=math.sin(2*3.14*i/50)/math.cos(2*3.14*i/50)
if(y>max):
max=y
elif(y<min):
min=y
i+=1
print(max)
print(min)
j=1
while j<=50:
y= math.ceil(((math.sin(2*3.14*j/50)/math.cos(2*3.14*j/50))-min)*50/(max-min))
for pr in range(int(y)):
print (" ",end='');
print ("*")
j+=1
ответ дан 29 окт 2015 в 8:19
If the number (positive or negative) is divided by zero in mathematics, the output will be undefined or of no value. Similarly, if the number (integer or float) is divided by zero in Python, the interpreter will throw a “ZeroDivisionError”. To resolve this error, various solutions are used in Python, such as the “if” statement and the “try-except” block.
This blog provides the reason for the error “float division by zero” with their solutions and examples. The following aspects are followed in this article:
- Reason: Dividing Floating Point Number By “0”
- Solution 1: Use if-Statement
- Solution 2: Use try-except Block
So, let’s get started!
Reason: Dividing Floating Point Number By “0”
The prominent reason which causes this error in Python is when a user tries to divide the floating point number by “0” in a program. The error snippet is shown below:
The above snippet shows “ZeroDivisionError” because the floating point number is divided by “0”.
Solution 1: Use if-Statement
To resolve this error, you can use the “if” statement to check if the divisor is equal to “0” or not. Here is a code example:
Code:
first_number = 56.4 second_number = 0 if second_number!=0: output = first_number / second_number else: output = 0 print(output)
In the above code:
- The “if” statement is utilized to check whether the divisor or the number which we are dividing by is equal to zero or not.
- If the number is not equal to zero, then the “if” block statement is executed and shows the division result.
- The else block is executed when the divisor is equal to zero.
The above output shows the value “0” because the divisor number is equal to “0”.
Solution 2: Use try-except Block
Another solution to handle this particular error is using the “try-except” block in the program. Let’s understand this concept via the below-given Python program.
Code:
first_number = 56.4 second_number = 0 try: output = first_number / second_number except ZeroDivisionError: output = 0 print(output)
In the above code:
- The “try” block executes when the divisor is not equal to zero.
- If the dividing number/divisor is equal to zero, then the “except” block handles the “ZeroDivisionError” and assigns a “0” value to the output variable.
The output shows that the try-except block successfully resolves the stated error.
That’s it from this guide!
Conclusion
The “ZeroDivisionError: float division by zero” occurs when a user tries to divide a floating point number by the value “0” in Python. To resolve this error, you can use the “if-else” statement to check whether the input number is equal to zero or not before performing the calculation. The “try-except” block is also used to handle the “ZeroDivisionError” in Python programs. This blog explained how to resolve the “float division by zero” error in Python using appropriate examples.
When working with numbers in Python, you might encounter the following error:
ZeroDivisionError: float division by zero
This error occurs when you attempt to divide a floating number with zero.
Python raises the ZeroDivisionError
because dividing a number with a zero returns an infinite number, which is impossible to measure in a programming language.
This tutorial will show you an example that causes this error and how to fix it
How to reproduce this error
Suppose you have two number variables where one of them is a float and the other is zero.
When you divide the float by zero as follows:
You get this output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
z = x / y
ZeroDivisionError: float division by zero
The error occurs because the y
variable is zero, so the division yields an infinite number that can’t be counted.
How to fix this error
To resolve this error, you need to prevent a division by zero from happening in your code.
One way to do this is to use the if
statement to check if the dividing number is zero. In this case, you have to check the value of the y
variable:
x = 9.5
y = 0
if y == 0:
print("Can't perform division: the y variable is 0")
z = 0
else:
z = x / y
Or you can also use a one-line if
statement as follows:
z = 0 if y == 0 else (x / y)
When the value of y
is zero, then set the value of z
as zero too. Otherwise, divide x
by y
and assign the result to z
.
Other similar errors
Besides float division by zero, the ZeroDivisionError
also has some alternatives:
ZeroDivisionError: integer division by zero
ZeroDivisionError: integer modulo by zero
ZeroDivisionError: float modulo by zero
Although the error message is slightly different, all these variants are caused by the same problem: you tried to divide or modulo the number by zero.
Here are some examples:
x = 5 / 0 # integer division by zero
y = 5 % 0 # integer modulo by zero
z = 7.5 % 0 # float modulo by zero
The solution to these errors is the same, you need to prevent the numbers from being divided or reduced using a zero.
I hope this tutorial helps you solve the error. Cheers! 🙌
By Lenin Mishra
in
python
—
Jan 15, 2022
Handling Zero Division exceptions in Python
A ZeroDivisionError
is raised when you try to divide by 0. This is part of the ArithmeticError Exception class.
Example 1
Code/Output
# integers
1/0
>>> ZeroDivisionError: division by zero
# floats
5.3/0
>>> ZeroDivisionError: float division by zero
# complex numbers
(1+2j)/0
>>> ZeroDivisionError: complex division by zero
Example 2 — decimal library
If you are working with a decimal library and you perform the division operation with a 0
, you get a DivisionByZero
error.
The DivisionByZero
eexception is decimal
libraries own exception type that derives from the ZeroDivisionError
exception.
Code
from decimal import Decimal
x = Decimal(1)
print(x/0)
Output
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]
Handling ZeroDivisionError in Python
You can handle ZeroDivisionError
errors by using the same exception class in your except block.
Code
# integers
try:
1/0
except ZeroDivisionError as e:
print(e)
# floats
try:
5.3/0
except ZeroDivisionError as e:
print(e)
# complex numbers
try:
(1+2j)/0
except ZeroDivisionError as e:
print(e)
Output
division by zero
float division by zero
complex division by zero
Hierarchy of ZeroDivisionError
The ZeroDivisionError
inherits from the ArithmeticError
class, which in turn inherits from the generic Exception
class.
->Exception
-->ArithmeticError
--->ZeroDivisionError
So you can catch all ZeroDivisionError
exceptions using the ArithmeticError
exception class too.
Code
# integers
try:
1/0
except ArithmeticError as e:
print(e, e.__class__)
# floats
try:
5.3/0
except ArithmeticError as e:
print(e, e.__class__)
# complex numbers
try:
(1+2j)/0
except ArithmeticError as e:
print(e, e.__class__)
Output
division by zero <class 'ZeroDivisionError'>
float division by zero <class 'ZeroDivisionError'>
complex division by zero <class 'ZeroDivisionError'>
Check out other Python Built-in Exception classes in Python.
In Python, a ZeroDivisionError
is raised when a division or modulo operation is attempted with a denominator or divisor of 0.
What Causes ZeroDivisionError
A ZeroDivisionError
occurs in Python when a number is attempted to be divided by zero. Since division by zero is not allowed in mathematics, attempting this in Python code raises a ZeroDivisionError
.
Python ZeroDivisionError Example
Here’s an example of a Python ZeroDivisionError
thrown due to division by zero:
a = 10
b = 0
print(a/b)
In this example, a number a
is attempted to be divided by another number b
, whose value is zero, leading to a ZeroDivisionError
:
File "test.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
How to Fix ZeroDivisionError in Python
The ZeroDivisionError
can be avoided using a conditional statement to check for a denominator or divisor of 0 before performing the operation.
The code in the earlier example can be updated to use an if
statement to check if the denominator is 0:
a = 10
b = 0
if b == 0:
print("Cannot divide by zero")
else:
print(a/b)
Running the above code produces the correct output as expected:
Cannot divide by zero
A try-except block can also be used to catch and handle this error if the value of the denominator is not known beforehand:
try:
a = 10
b = 0
print(a/b)
except ZeroDivisionError as e:
print("Error: Cannot divide by zero")
Surrounding the code in try-except blocks like the above allows the program to continue execution after the exception is encountered:
Error: Cannot divide by zero
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!