简体   繁体   中英

Solving and plotting functions in Python

The proplem

I want to solve the above functions to plot xAxis vs yAxis for x between [0:2]. I started with the first function, "det", and used sympy library and the (solve, nsolve) methods to find the solution "yAxis for every xAxis" but I got an error that says "pop form an empty set". I am not sure if I am using the right syntax for the natural log function (ln) and even if I am using the right library "sympy" and its methods. Could anyone please help me understand what exactly I am doing wrong and if there is a better way to evaluate yAxis and plot the functions. Here is my code:

import math
import numpy as np
import sympy as sym
from sympy import *

y = sym.symbols('y')
xAxis = np.arange(start=0, stop=2, step=0.1)
yAxis = []
for x in xAxis:
    det = sym.Eq ((x*y*(y*sym.log((1+sym.log((x*y+1),math.e)),math.e)+(y-1)*sym.log((x*y+1),math.e)+y)/((x*y+1)*sym.log((x*y+1),math.e)*((y-1)*sym.log((x*y+1),math.e)+y)))-1)
    sol = sym.nsolve(det,y)
    yAxis.append(sol[0])

This is actually a "nice" equation that can be plotted with plot_implicit . "Nice" because it is hard to plot, it pushes the algorithms to their limit in terms of capabilities and forces us to analyze what we are doing.

I'm going to use the SymPy Plotting Backend module because it better deals with implicit plots.

import sympy as sym
det = sym.Eq ((x*y*(y*sym.log((1+sym.log((x*y+1))))+(y-1)*sym.log((x*y+1))+y)/((x*y+1)*sym.log((x*y+1))*((y-1)*sym.log((x*y+1))+y))), 1)
from spb import *
plot_implicit(det, (x, 0, 2))

在此处输入图像描述

Now we need to figure out if the plot is correct. At denominator, det contains terms like log(x * y + 1) : when x=0 or y=0 those terms goes to zero and the function doesn't exist. So, the horizontal line that you see in the plot is wrong.

When x is positive and y is negative, there will combinations of these two values at which the function doesn't exist. For example, let's consider x=0.25 :

plot(det.rewrite(Add).subs(x, 0.25), (y, -2.5, 0), ylim=(-100, 10))

在此处输入图像描述

For x=0.25 , det doesn't exist if y < -1.9something . I believe that the vertical line indicates numerical errors. Hence, in the initial plot the curved line for 0 < x < 1 and y < 0 is wrong.

What about the curved line for x > 1 and y > 0 ? Again, let's consider a fixed x, for example x=1.75 :

plot(det.rewrite(Add).subs(x, 1.75), (y, 0, 1), ylim=(-10, 10))

在此处输入图像描述

There is a discontinuity there, the function doesn't exists but the algorithm got confused.

At end, there is only one correct line and we can plot it with:

plot_implicit(det, (x, 0, 2), (y, 0.5, 10), ylim=(0, 10))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM