Sick Gaming
[Tut] Python Math Domain Error (How to Fix This Stupid Bug) - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python Math Domain Error (How to Fix This Stupid Bug) (/thread-98386.html)



[Tut] Python Math Domain Error (How to Fix This Stupid Bug) - xSicKxBot - 11-21-2020

Python Math Domain Error (How to Fix This Stupid Bug)

<div><p>You may encounter a special <code>ValueError</code> when working with Python’s <a href="https://blog.finxter.com/python-math-module/" target="_blank" rel="noreferrer noopener" title="Python Math Module [Ultimate Guide]"><code>math</code> module</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: math domain error</pre>
<p>Python raises this error when you try to do something that is not mathematically possible or mathematically defined.</p>
<p>To understand this error, have a look at the definition of the <strong>domain</strong>:</p>
<p>“<em>The <strong>domain </strong>of a function is the complete set of possible values of the independent variable. Roughly speaking, the <strong>domain</strong> is the set of all possible (input) x-values which result in a valid (output) y-value.</em>” (<a href="https://www.intmath.com/functions-and-graphs/2a-domain-and-range.php" target="_blank" rel="noreferrer noopener" title="https://www.intmath.com/functions-and-graphs/2a-domain-and-range.php">source</a>)</p>
<p class="has-pale-cyan-blue-background-color has-background">The domain of a function is the set of all possible input values. If Python throws the <code>ValueError: math domain error</code>, you’ve passed an undefined input into the <code>math</code> function. Fix the error by passing a valid input for which the function is able to calculate a numerical output.</p>
<p>Here are a few examples:</p>
<h2>Python Math Domain Error Sqrt</h2>
<p>The math domain error appears if you pass a negative argument into the <code>math.sqrt()</code> function. It’s mathematically impossible to calculate the square root of a negative number without using complex numbers. Python doesn’t get that and throws a <code>ValueError: math domain error</code>. </p>
<figure class="wp-block-image size-large"><img loading="lazy" width="736" height="396" src="https://blog.finxter.com/wp-content/uploads/2020/11/image-30.png" alt="Graph square root" class="wp-image-17128" srcset="https://blog.finxter.com/wp-content/uploads/2020/11/image-30.png 736w, https://blog.finxter.com/wp-content/uploads/2020/11/image-30-300x161.png 300w, https://blog.finxter.com/wp-content/uploads/2020/11/image-30-150x81.png 150w" sizes="(max-width: 736px) 100vw, 736px" /></figure>
<p>Here’s a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from math import sqrt
print(sqrt(-1)) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\code.py", line 2, in &lt;module> print(sqrt(-1))
ValueError: math domain error '''</pre>
<p>You can fix the math domain error by using the <code>cmath</code> package that allows the creation of complex numbers:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from cmath import sqrt
print(sqrt(-1))
# 1j</pre>
<h2>Python Math Domain Error Log</h2>
<p>The <code>math domain error</code> for the <code>math.log()</code> function appears if you pass a zero value into it—the logarithm is not defined for value 0. </p>
<figure class="wp-block-image size-large"><img loading="lazy" width="687" height="391" src="https://blog.finxter.com/wp-content/uploads/2020/11/image-29.png" alt="Graph logarithm" class="wp-image-17124" srcset="https://blog.finxter.com/wp-content/uploads/2020/11/image-29.png 687w, https://blog.finxter.com/wp-content/uploads/2020/11/image-29-300x171.png 300w, https://blog.finxter.com/wp-content/uploads/2020/11/image-29-150x85.png 150w" sizes="(max-width: 687px) 100vw, 687px" /></figure>
<p>Here’s the code on an input value outside the domain of the logarithm function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from math import log
print(log(0))</pre>
<p>The output is the math domain error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\code.py", line 3, in &lt;module> print(log(0))
ValueError: math domain error</pre>
<p>You can fix this error by passing a valid input value into the <code>math.log()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from math import log
print(log(0.000001))
# -13.815510557964274</pre>
<p>This error can sometimes appear if you pass a very small number into it—Python’s float type cannot express all numbers. To pass a value “close to 0”, use the <code>Decimal</code> module with higher precision, or pass a very small input argument such as:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">math.log(sys.float_info.min)</pre>
<h2>Python Math Domain Error Acos</h2>
<p>The <code>math domain error</code> for the <code>math.acos()</code> function appears if you pass a value into it for which it is not defined—arccos is only defined for values between -1 and 1. </p>
<figure class="wp-block-image size-large"><img loading="lazy" width="717" height="391" src="https://blog.finxter.com/wp-content/uploads/2020/11/image-27.png" alt="Graph arccos(x)" class="wp-image-17118" srcset="https://blog.finxter.com/wp-content/uploads/2020/11/image-27.png 717w, https://blog.finxter.com/wp-content/uploads/2020/11/image-27-300x164.png 300w, https://blog.finxter.com/wp-content/uploads/2020/11/image-27-150x82.png 150w" sizes="(max-width: 717px) 100vw, 717px" /></figure>
<p>Here’s the wrong code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
print(math.acos(2))</pre>
<p>The output is the math domain error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\code.py", line 3, in &lt;module> print(math.acos(2))
ValueError: math domain error</pre>
<p>You can fix this error by passing a valid input value between [-1,1] into the <code>math.acos()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
print(math.acos(0.5))
# 1.0471975511965979</pre>
<h2>Python Math Domain Error Asin</h2>
<p>The <code>math domain error</code> for the <code>math.asin()</code> function appears if you pass a value into it for which it is not defined—arcsin is only defined for values between -1 and 1.</p>
<figure class="wp-block-image size-large"><img loading="lazy" width="734" height="396" src="https://blog.finxter.com/wp-content/uploads/2020/11/image-28.png" alt="Graph Arcsin" class="wp-image-17121" srcset="https://blog.finxter.com/wp-content/uploads/2020/11/image-28.png 734w, https://blog.finxter.com/wp-content/uploads/2020/11/image-28-300x162.png 300w, https://blog.finxter.com/wp-content/uploads/2020/11/image-28-150x81.png 150w" sizes="(max-width: 734px) 100vw, 734px" /></figure>
<p>Here’s the erroneous code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
print(math.asin(2))</pre>
<p>The output is the math domain error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\code.py", line 3, in &lt;module> print(math.asin(2))
ValueError: math domain error</pre>
<p>You can fix this error by passing a valid input value between [-1,1] into the <code>math.asin()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
print(math.asin(0.5))
# 0.5235987755982989</pre>
<h2>Python Math Domain Error Pow</h2>
<p>The <code>math domain error</code> for the <code>math.pow(a,b)</code> function to calculate a**b appears if you pass a negative base value into it and try to calculate a negative power of it. The reason it is not defined is that any negative number to the power of 0.5 would be the square number—and thus, a complex number. But complex numbers are not defined by default in Python!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
print(math.pow(-2, 0.5))</pre>
<p>The output is the math domain error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\code.py", line 3, in &lt;module> print(math.pow(-2, 0.5))
ValueError: math domain error</pre>
<p>If you need a complex number, a<sup>b</sup> must be rewritten into e<sup>b ln a</sup>. For example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import cmath
print(cmath.exp(0.5 * cmath.log(-2)))
# (8.659560562354932e-17+1.414213562373095j)</pre>
<p>You see, it’s a complex number!</p>
<h2>NumPy Math Domain Error — np.log(x)</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import matplotlib.pyplot as plt # Plotting y = log(x)
fig, ax = plt.subplots()
ax.set(xlim=(-5, 20), ylim=(-4, 4), title='log(x)', ylabel='y', xlabel='x')
x = np.linspace(-10, 20, num=1000)
y = np.log(x) plt.plot(x, y)</pre>
<figure class="wp-block-image"><img loading="lazy" width="391" height="279" src="https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png" alt="" class="wp-image-8765" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png 391w, https://blog.finxter.com/wp-content/uploads/2020/05/image-64-300x214.png 300w" sizes="(max-width: 391px) 100vw, 391px" /></figure>
<p>This is the graph of <code>log(x)</code>. Don’t worry if you don’t understand the code, what’s more important is the following point. You can see that log(x) tends to negative infinity as x tends to 0. Thus, it is mathematically meaningless to calculate the log of a negative number. If you try to do so, Python raises a math domain error.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.log(-10)
Traceback (most recent call last): File "&lt;stdin>", line 1, in &lt;module>
ValueError: math domain error</pre>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/python-math-domain-error/" target="_blank" rel="noopener noreferrer">Python Math Domain Error (How to Fix This Stupid Bug)</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/11/20/python-math-domain-error-how-to-fix-this-stupid-bug/