+ 1

[Solved] How to handle complex numbers in matplotlib

Hello there! The code below draws the graph of a mathematical (for example: x**2 , 2*x+2, cos(x)), but when it comes to logarithms, the following error occurs: Sample input: ln(x) 2 Last 3 lines of Output: File "../Playground//site-packages../Playground/", line 350, in __float__ raise TypeError("Cannot convert complex to float") TypeError: Cannot convert complex to float https://sololearn.com/compiler-playground/cNPQj468e5wk/?ref=app

6th Apr 2024, 12:18 PM
Shreyash Roopnah
Shreyash Roopnah - avatar
4 Réponses
+ 3
Read the sympy documentation. log() function returns complex result for negative numbers. https://docs.sympy.org/latest/modules/functions/elementary.html#sympy.functions.elementary.exponential.log "log represents the principal branch of the natural logarithm. As such it has a branch cut along the negative real axis and returns values having a complex argument:
6th Apr 2024, 2:14 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Your y_list1 variable contains complex numbers. This is definitely a mistake, you cannot plot complex numbers on a single real number axis, and the logarithm of any real number is not complex. You should not overuse eval.
6th Apr 2024, 1:45 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Got it! I just verified and I was able to debug my program... Thanks for your help!
6th Apr 2024, 2:29 PM
Shreyash Roopnah
Shreyash Roopnah - avatar
0
So... What should I do then?...
6th Apr 2024, 1:54 PM
Shreyash Roopnah
Shreyash Roopnah - avatar