scipy-lectures / scientific-python-lectures

Tutorial material on the scientific Python ecosystem
https://lectures.scientific-python.org
Other
3.11k stars 1.19k forks source link

Avoid warning about taking log of 0 #624

Closed jarrodmillman closed 1 year ago

jarrodmillman commented 1 year ago

Avoid

131     array([ True, False, False, False])
132
133 **Transcendental functions:**
134
135 .. sourcecode:: pycon
136
137     >>> a = np.arange(5)
138     >>> np.sin(a)
139     array([ 0.        ,  0.84147098,  0.90929743,  0.14112001, -0.7568025 ])
140     >>> np.log(a)
UNEXPECTED EXCEPTION: RuntimeWarning('divide by zero encountered in log')
Traceback (most recent call last):
  File "/usr/lib64/python3.11/doctest.py", line 1351, in __run
    exec(compile(example.source, filename, "single",
  File "<doctest operations.rst[34]>", line 1, in <module>
RuntimeWarning: divide by zero encountered in log
/home/jarrod/src/scipy-lecture-notes/intro/numpy/operations.rst:140: UnexpectedException
stefanv commented 1 year ago

This is fine as a technical fix, although thinking about thge pedagogical value of taking log(sin(...)) is dubious. A much more common operation is log of exp, so perhaps we could replace sin with exp, and make the numbers negative:

np.log(np.exp(np.arange(-10, -100, -10)))

Or, another one that may provide even more insight:

np.log10(np.logspace(-10, -100))
jarrodmillman commented 1 year ago

Isn't this just the log of np.arange(5)[1:]? And not log of np.sin(np.arange(5))[1:].

stefanv commented 1 year ago

I see; well, the principle holds, we can just transform the numbers into something that has a valid log. E.g., a_exp = np.exp(a) and then take the log of that to get back to the original numbers.