def plot(): e = Symbol('e') y = Symbol('y') n = Symbol('n') generalized_vc_bounds = (original_vc_bound, rademacher_penalty_bound) growth_function_bound = generate_growth_function_bound(50) p1 = plot(original_vc_bound(n, 0.05, growth_function_bound), (n,100, 15000), show=False, line_color = 'black') p2 = plot(rademacher_penalty_bound(n, 0.05, growth_function_bound), (n,100, 15000), show=False, line_color = 'blue') plot_implicit(Eq(e, parrondo_van_den_broek_right(e, n, 0.05, growth_function_bound)), (n,100, 15000), (e,0,5)) # plot_implicit(Eq(e, devroye(e, n, 0.05, growth_function_bound)), (n,100, 1000), (e,0,5)) p1.extend(p2) p1.show()
def plot_and_save(expr, *args, **kwargs): name = kwargs.pop('name', '') dir = kwargs.pop('dir', None) p = plot_implicit(expr, *args, **kwargs) p.save(tmp_file(dir=dir, name=name)) # Close the plot to avoid a warning from matplotlib p._backend.close()
def test_region_and(): matplotlib = import_module("matplotlib", min_module_version="1.1.0", catch=(RuntimeError, )) if not matplotlib: skip("Matplotlib not the default backend") from matplotlib.testing.compare import compare_images test_directory = os.path.dirname(os.path.abspath(__file__)) try: temp_dir = mkdtemp() TmpFileManager.tmp_folder(temp_dir) x, y = symbols("x y") r1 = (x - 1)**2 + y**2 < 2 r2 = (x + 1)**2 + y**2 < 2 test_filename = tmp_file(dir=temp_dir, name="test_region_and") cmp_filename = os.path.join(test_directory, "test_region_and.png") p = plot_implicit(r1 & r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_or") cmp_filename = os.path.join(test_directory, "test_region_or.png") p = plot_implicit(r1 | r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_not") cmp_filename = os.path.join(test_directory, "test_region_not.png") p = plot_implicit(~r1, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_xor") cmp_filename = os.path.join(test_directory, "test_region_xor.png") p = plot_implicit(r1 ^ r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) finally: TmpFileManager.cleanup()
def draw(self, xmin, xmax, ymin, ymax): x = symbols('x') y = symbols('y') function = self.equation('x', 'y', False) as1, as2 = self.asymptote('x', 'y', False) p1 = plot_implicit(function, (x, xmin, xmax), (y, ymin, ymax), title='Graph of the Hyperbola', line_color='blue', show=False) p2 = plot_implicit(as1, (x, xmin, xmax), (y, ymin, ymax), line_color='crimson', show=False) p3 = plot_implicit(as2, (x, xmin, xmax), (y, ymin, ymax), line_color='crimson', show=False) p1.append(p2[0]) p1.append(p3[0]) p1.show()
def plot_equation(eq: Equality, x_var=None, y_var=None, ): # 创建plot但不绘制 plot = plot_implicit(eq, x_var, y_var, show=False) # 自己初始化一个绘制引擎 matplot = MatplotlibBackend(plot) # backend 给每个plot创建一个单独的坐标系,所以要取出坐标系来单独设置 ax: Axes = matplot.ax[0] ax.set_aspect('equal') ax.grid(True) matplot.show()
def plot(): e = Symbol('e') y = Symbol('y') n = Symbol('n') generalized_vc_bounds = (original_vc_bound, rademacher_penalty_bound) growth_function_bound = generate_growth_function_bound(50) p1 = plot(original_vc_bound(n, 0.05, growth_function_bound), (n, 100, 15000), show=False, line_color='black') p2 = plot(rademacher_penalty_bound(n, 0.05, growth_function_bound), (n, 100, 15000), show=False, line_color='blue') plot_implicit( Eq(e, parrondo_van_den_broek_right(e, n, 0.05, growth_function_bound)), (n, 100, 15000), (e, 0, 5)) # plot_implicit(Eq(e, devroye(e, n, 0.05, growth_function_bound)), (n,100, 1000), (e,0,5)) p1.extend(p2) p1.show()
def ezplot(expr, color): try: plot = plot_implicit(self.parseEquation(expr, x, y), (x, varXBegin, varXEnd), (y, varYBegin, varYEnd), show=False, line_color=color) except Exception as e: plot = None if not plot: print("Failed to plot expression: ", expr) return plot
def plotXhh(mh1_0, mh2_0, r, Xhh_cut, mh1_min, mh1_max, mh2_min, mh2_max, color): mh1, mh2 = sp.symbols('mh1 mh2') sg_expr = ((mh1 - mh1_0) / (r * mh1))**2 + ((mh2 - mh2_0) / (r * mh2))**2 sg_eq = sp.Eq(sg_expr, Xhh_cut**2) plot = sp.plot_implicit(sg_eq, x_var=(mh1, mh1_min, mh1_max), y_var=(mh2, mh2_min, mh2_max), show=False, axis_center=(mh1_min, mh2_min)) x, y = zip(*[(x_int.mid, y_int.mid) for x_int, y_int in plot[0].get_points()[0]]) x, y = list(x), list(y) plt.plot(x, y, '.', markersize=0.5, color=color)
def draw_plots(): x, y = sy.symbols('x, y') func1 = sy.Or(sy.Eq(x**2 + y**2 - 4, 0), sy.Eq(x**4 - y - 4, 0)) func2 = sy.Or(sy.Eq((x - 1)**2 + y**2 - 9, 0), sy.Eq(sy.tan(x - 1) - y**3, 0)) func3 = sy.Or(sy.Eq(x**2 + y**2 - 4, 0), sy.Eq(x**2 + y**2 - 1, 0)) sy.plot_implicit(func1) sy.plot_implicit(func2, (x, -4, 6), (y, -5, 5)) sy.plot_implicit(func3)
import matplotlib.patches as patches init_printing() var('x,y', real=True) f = (x - 0.5)**3 - 4 * (x - 0.5)**2 + 3 * (x - 0.5) + 1 + 2.5 # pts criticos pc = solve(f.diff()) p = plot(f, (x, 0.5, 3.25), line_color='blue', show=False) q = plot(-0.5, (x, -0.5, 3.75), line_color='none', show=False) p.extend(q) q = plot(5, (x, -0.5, 3.75), line_color='none', show=False) p.extend(q) q = plot_implicit(y <= f, (x, 0.5, 3.25), (y, 0, 5), show=False, line_color="gray") p.extend(q) p.xlabel = '$x$' p.ylabel = '$y$' p.save('fig_geointdef.png') fig = p._backend.fig ax = fig.axes[0] ax.grid('on') ax.set_xticks([0.5, 3.25]) ax.set_xticklabels(["$a$", "$b$"]) ax.set_yticks([float(f.subs(x, 0.5)), float(f.subs(x, 3.25))]) ax.set_yticklabels([]) ax.text(3.25, 2.5, "$y=f(x)$")
from sympy import plot_implicit, cos, sin, symbols, Eq, And, plot from sympy.parsing.sympy_parser import parse_expr points = [] for i in xrange(0,10): for j in xrange(0,10): points.append(complex(i,j)) p = 20000 x,y = symbols('x y') func = '' for i in xrange(len(points) - 1): func += ('((x-'+str(points[i].real)+')**2 + (y-'+str(points[i].imag)+')**2)*') func += ('((x-'+str(points[len(points)-1].real)+')**2 + (y-'+str(points[len(points)-1].imag)+')**2)') func += ('-' + str(p**2)) print(func) print(Eq(parse_expr(func))) plot_implicit(Eq(parse_expr(func)), (x,-10,10), (y,-10,10))
L = (a + c) / 2.0 R = (c + b) / 2.0 Fa = func.subs(x, a) Fb = func.subs(x, b) Fc = func.subs(x, c) FL = func.subs(x, L) FR = func.subs(x, R) Fmin = min(Fa, Fb, Fc, FL, FR) if Fmin == Fa or Fmin == FL: b = c c = L elif Fmin == Fb or Fmin == FR: a = c c = R elif Fmin == Fc: a = L b = R print(c) sp.plot(func, (x, -1, 4), line_color='r') x, y = sp.symbols("x y") hp = sp.plot_implicit(sp.Eq(x**2 + y**2, 4), (x, -3, 3), (y, -3, 3)) fig = hp._backend.fig ax = hp._backend.ax xx = yy = np.linspace(-3, 3) ax.plot(xx, yy) # y = x ax.plot([0], [0], 'o') # Point (0,0) ax.set_aspect('equal', 'datalim') fig.canvas.draw()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sympy as sym if __name__ == "__main__": x, y = sym.symbols('x, y') f = x**2 + y**2 - 1 g = sym.tan(x * y + 0.5) - x**2 args = (x, -2, 2), (y, -2, 2) curve_f = sym.plot_implicit(sym.Eq(f, 0), *args, show=False) curve_g = sym.plot_implicit(sym.Eq(g, 0), *args, show=False) curve_g.extend(curve_f) curve_g.show()
""" 你是公司营销系统的工程师。 你们某个商品的购买概率和补贴额的关系为,p(x) = 0.05 x + 0.2。 该商品原价 m 为 16 元,成本价 c 为 8 元,求利润最大的补贴额应该是多少? """ from sympy import expand, symbols, plot_implicit, Eq import math from sympy.abc import x, y p1 = plot_implicit(Eq(-0.0025 * x**2 + 0.38 * x + 1.56, y)) x = symbols('x') print(expand((16 - 8 - 0.05 * x - 0.2) * (0.05 * x + 0.2))) def getSubsidy(k, b, m, c): rx = [-k, k * (m - c) - b, b * (m - c)] # -系数 (m-c-kx-0.2)*(kx+0.2) # (16-8-0.05x-0.2)*(0.05x+0.2) rpx = [-2 * k, k * (m - c) - b] return -rpx[1] / rpx[0] # print(getSubsidy(0.05, 0.2, 16, 8))
for i in range(time): x_list.append(x_list[i] + (x_movement(x_list[i], y_list[i])) * dt) y_list.append(y_list[i] + (y_movement(x_list[i], y_list[i])) * dt) ax.plot(x_list, y_list, color="black") # Quiverplot # create a grid and set the dir vecs X, Y = np.meshgrid(x_line, y_line) x_dir, y_dir = x_movement(X, Y), y_movement(X, Y) # prepare the colour and normalization factor norm = np.sqrt(x_dir**2 + y_dir**2) #Normalize if normalize: x_dir /= norm y_dir /= norm plt.quiver(X, Y, x_dir, y_dir, norm, pivot='mid') # Plot Nullclines p1 = sm.plot_implicit(dot_x_Equal, (x, x_min, x_max), (y, y_min, y_max), show=False) p2 = sm.plot_implicit(dot_y_Equal, (x, x_min, x_max), (y, y_min, y_max), show=False) move_sympyplot_to_axes(p1, ax) move_sympyplot_to_axes(p2, ax) plt.show()
M_t, a, psi, G, theta, z, x, y = sp.var('M_t, a, psi, G, theta, Z, X, Y') C = sp.var(['C_' + str(i) for i in range(10)]) #criando as bordas da seção transversal (triângulo) f = sp.Matrix([ y + sp.sqrt(3) * x - 2 * a, y - sp.sqrt(3) * x - 2 * a, y - a, ]) p2 = [] for i in f: p1 = sp.plot_implicit(sp.Eq(i.subs({a: 1}), 0), (x, -4, 4), (y, -4, 4)) p2.append(p1) [p2[0].extend(i) for i in p2] p2[0].show() #criação de psi dada no exercício psi, alpha, mu, g = sp.var('psi, alpha, mu, G') theta = sp.Function('theta')(x, y, z) psi = -g * theta.diff(z) * ((x**2 + y**2) / 2 - (x**3 - 3 * x * y**2) / (2 * a) - 2 * a**2 / 27) T = sp.zeros(3) T[0, 1] = T[1, 0] = +psi.diff(y, ).simplify()
filter (1 pole, 1 zero) to be used in a series connection... p2 is always a hyperbola that goes trough 0 and 1. For continuity around w=0.5*pi, we seem to have to use the lower arm (the one that goes through 0). However, that solution tends to grow large for small w. ..hmm - this soltuion is very small around w=pi/2 but with the upper arm, there's a intersection only for certain values of w ..maybe the 1 pole / 1 zero idea is not really good, after all and we should stick to 1 pole / 0 zero """ from sympy import plot_implicit, symbols, sin, cos, tan, pi w = 0.45 * pi # cutoff frequency # intermediate parameters: s = sin(w) c = cos(w) t = tan((w - pi) / 4) #define symbols and equations: x, y = symbols('x y') # x=b0, y=b1 a = x + y - 1 # a = a1 = b0+b1-1 e1 = 2 * (1 - c) * (x + y - x * y - 1) + x**2 + y**2 e2 = t * (x + a * y + (y + a * x) * c) - s * (a * x - y) # plot the two conics: p1 = plot_implicit(e1, (x, -2, 2), (y, -2, 2)) p2 = plot_implicit(e2, (x, -2, 2), (y, -2, 2)) #p2 = plot_implicit(e2)
from sympy import plot_implicit, symbols, Eq, solve x, y = symbols('x y') eq = Eq((x**2 + y**2 - 1)**3 - (x**2) * (y**3)) plot_implicit(eq)
def plot_and_save(name): x = Symbol('x') y = Symbol('y') z = Symbol('z') #implicit plot tests plot_implicit(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(Eq(y**2, x**3 - x), (x, -5, 5), (y, -4, 4)).save(tmp_file(name)) plot_implicit(y > 1 / x, (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y < 1 / tan(x), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y >= 2 * sin(x) * cos(x), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y <= x**2, (x, -3, 3), (y, -1, 5)).save(tmp_file(name)) #Test all input args for plot_implicit plot_implicit(Eq(y**2, x**3 - x)).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False, points=500).save(tmp_file()) plot_implicit(y > x, (x, -5, 5)).save(tmp_file()) plot_implicit(And(y > exp(x), y > x + 2)).save(tmp_file()) plot_implicit(Or(y > x, y > -x)).save(tmp_file()) plot_implicit(x**2 - 1, (x, -5, 5)).save(tmp_file()) plot_implicit(x**2 - 1).save(tmp_file()) plot_implicit(y > x, depth=-5).save(tmp_file()) plot_implicit(y > x, depth=5).save(tmp_file()) plot_implicit(y > cos(x), adaptive=False).save(tmp_file()) plot_implicit(y < cos(x), adaptive=False).save(tmp_file()) plot_implicit(And(y > cos(x), Or(y > x, Eq(y, x)))).save(tmp_file()) plot_implicit(y - cos(pi / x)).save(tmp_file()) #Test plots which cannot be rendered using the adaptive algorithm #TODO: catch the warning. plot_implicit(Eq(y, re(cos(x) + I*sin(x)))).save(tmp_file(name)) with warnings.catch_warnings(record=True) as w: plot_implicit(x**2 - 1, legend='An implicit plot').save(tmp_file()) assert len(w) == 1 assert issubclass(w[-1].category, UserWarning) assert 'No labeled objects found' in str(w[0].message)
def plot(self, filename, input_epsilon): """ ------------------------------------------------------------------ moving_delta_epsilon: If the associated proof has been finished, it will create a gif of the delta-epsilon lines. ------------------------------------------------------------------ Parameters: filename - where to save graph ------------------------------------------------------------------ """ # we need to consider the following cases: # delta epsilon proofs => regular DONE # N/M or both option # mins on delta/epsilon/N/M? # issues/things to consider: # vertical delta lines not working # too much memory being consumed due to plotting. # directory vs. file x = sm.Symbol('x') y = sm.Symbol('y') graphs_extend = [] # if proof is done if self.current_equation == self.epsilon: # find delta/epsilon bounds input_delta = self.delta_exp.subs(self.epsilon, input_epsilon) # is it delta? if str(self.delta) == 'delta': # is it bounded? if self.delta_bound != 0 and input_delta > self.delta_bound: input_delta = self.delta_bound # create bounds x_upper_bound = self.x0 + input_delta x_lower_bound = self.x0 - input_delta x_dim = (x, self.x0 - input_delta * 3, self.x0 + input_delta * 3) # is it N? else: if self.x0 == sm.oo: x_lower_bound = input_delta x_upper_bound = None x_dim = (x, x_lower_bound - x_lower_bound * 0.5, x_lower_bound + x_lower_bound * 0.5) else: x_lower_bound = None x_upper_bound = input_delta x_dim = (x, x_upper_bound - x_upper_bound * 0.5, x_upper_bound + x_upper_bound * 0.5) # is it epsilon? if str(self.epsilon) == 'epsilon': y_upper_bound = self.limit + input_epsilon y_lower_bound = self.limit - input_epsilon graphs_extend.append( splot(y_lower_bound, show=False, line_color="red")) graphs_extend.append( splot(y_upper_bound, show=False, line_color="red")) y_dim = (y, self.limit - input_epsilon * 3, self.limit + input_epsilon * 3) # is it M? else: if self.limit == sm.oo: y_lower_bound = input_epsilon graphs_extend.append( splot(y_lower_bound, show=False, line_color="red")) y_dim = (y, y_lower_bound - y_lower_bound * 0.5, y_lower_bound + y_lower_bound * 0.5) else: y_upper_bound = input_epsilon graphs_extend.append( splot(y_upper_bound, show=False, line_color="red")) y_dim = (y, y_upper_bound - y_upper_bound * 0.5, y_upper_bound + y_upper_bound * 0.5) # create graphs for the x axis graphs_extend.append( plot_implicit(sm.Eq(x, x_upper_bound), x_dim, y_dim, line_color="blue", show=False)) graphs_extend.append( plot_implicit(sm.Eq(x, x_lower_bound), x_dim, y_dim, line_color="blue", show=False)) fx_graph = splot(self.fx, show=False, xlim=(x_dim[1], x_dim[2]), ylim=(y_dim[1], y_dim[2]), line_color="black") # merge graphs for graph in graphs_extend: fx_graph.extend(graph) fx_graph.save(filename)
def main(): vca = VCA(eps=0.005, max_dimension=4) vca.fit(np.array([[-1, 0], [1, 0], [0, 1], [0, -1]])) print vca.components_ for fn in vca.components_: plot_implicit(fn)
import sympy as sp import pandas as pd import matplotlib x, y = sp.symbols('x y') f = sp.sin(x - 0.4 * y) - x + y**2 g = (y + 0.1)**2 + x**2 - 0.7 plot = sp.plot_implicit(sp.Eq(f, 0), show=False, line_color='blue') plot.extend(sp.plot_implicit(sp.Eq(g, 0), show=False, line_color='green')) plot.show() def newton_system(x, y, f, g, x0, y0): dfdx = f.diff(x) dfdy = f.diff(y) dgdx = g.diff(x) dgdy = g.diff(y) d = dfdx * dgdy - dgdx * dfdy dx = f * dgdy - g * dfdy dy = dfdx * g - dgdx * f xs, ys, norms, fs, gs = [], [], [], [], [] xk, yk = x0, y0 while True: new_x = xk - (dx / d).evalf(subs={x: xk, y: yk}) new_y = yk - (dy / d).evalf(subs={x: xk, y: yk}) xs.append(new_x) ys.append(new_y)
break xk = xk_1 yk = yk_1 k += 1 data = xx, yy, differ, val_f, val_g columns = ["x_k", "y_k", "norma", "f(x_k, y_k)", "g(x_k, y_k)"] df = pd.DataFrame(data, columns).T df.columns.name = "k" return df, val x, y = sp.symbols('x y') plt1 = sp.plot_implicit(sp.Eq((y + 0.1)**2 + x**2 - 0.2, 0), (x, -0.7, 0.7), (y, -0.7, 0.7), show=False) plt2 = sp.plot_implicit(sp.Eq(x - y**2 - 0.37731, 0), (x, -1, 1), (y, -1, 1), show=False) plt1.extend(plt2) plt1.show() #(y + 0.1) ** 2 + x ** 2 = 0.2 #x - y ** 2 = 0.37731 f = lambda x, y: (y + 0.1)**2 + x**2 - 0.2 g = lambda x, y: x - y**2 - 0.37731 df_x = lambda x, y: 2 * x df_y = lambda x, y: 2 * y + 0.2 dg_x = lambda x: 1 dg_y = lambda y: -2 * y eps = 0.00001
def plot_and_save(): x = Symbol('x') y = Symbol('y') z = Symbol('z') #implicit plot tests plot_implicit(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2)).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), (x, -5, 5), (y, -4, 4)).save(tmp_file()) plot_implicit(y > 1 / x, (x, -5, 5), (y, -2, 2)).save(tmp_file()) plot_implicit(y < 1 / tan(x), (x, -5, 5), (y, -2, 2)).save(tmp_file()) plot_implicit(y >= 2 * sin(x) * cos(x), (x, -5, 5), (y, -2, 2)).save(tmp_file()) plot_implicit(y <= x**2, (x, -3, 3), (y, -1, 5)).save(tmp_file()) #Test all input args for plot_implicit plot_implicit(Eq(y**2, x**3 - x)).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False, points = 500).save(tmp_file()) plot_implicit(y > x, (x, -5, 5)).save(tmp_file()) plot_implicit(And(y > exp(x), y > x + 2)).save(tmp_file()) plot_implicit(Or(y > x, y > -x)).save(tmp_file()) plot_implicit(x**2 - 1, (x, -5, 5)).save(tmp_file()) plot_implicit(x**2 - 1).save(tmp_file()) plot_implicit(y > x, depth = -5).save(tmp_file()) plot_implicit(y > x, depth = 5).save(tmp_file()) plot_implicit(y > cos(x), adaptive=False).save(tmp_file()) plot_implicit(y < cos(x), adaptive=False).save(tmp_file()) plot_implicit(And(y > cos(x), Or(y > x, Eq(y, x)))).save(tmp_file()) #Test plots which cannot be rendered using the adaptive algorithm #TODO: catch the warning. plot_implicit(Eq(y, re(cos(x) + I*sin(x)))).save(tmp_file())
QDA_score = np.diag(QDA(mu0, mu1, cov0, cov1, data.T)) QDA_result = np.array(QDA_score > 0) # LDA plot w = (mu1 - mu0).T.dot(np.linalg.inv(cov)) b = -1 / 2 * ((mu1.T).dot(np.linalg.inv(cov)).dot(mu1) - (mu0.T).dot(np.linalg.inv(cov)).dot(mu0))[0][0] x = np.arange(0, 6, 0.1) y = (w[0, 0] * x + b) / (-w[0, 1]) plt.scatter(x=data[:, 0], y=data[:, 1], c=LDA_result.reshape(-1)) plt.plot(x, y) plt.xlabel('data[:,0]') plt.ylabel('data[:,1]') plt.title('LDA') plt.show() # QDA plot from sympy import plot_implicit, cos, sin, symbols, Eq, And x, y = symbols('x y') X = np.array([x, y]).reshape((2, 1)) diff1 = np.linalg.inv(cov0) - np.linalg.inv(cov1) diff2 = np.linalg.inv(cov0).dot(mu0) - np.linalg.inv(cov1).dot(mu1) threshold = 1/2*((mu1.T).dot(np.linalg.inv(cov)).dot(mu1)-(mu0.T).dot(np.linalg.inv(cov)).dot(mu0))[0][0] + \ 1/2*np.log(np.linalg.det(cov1)/np.linalg.det(cov0)) expr = 1 / 2 * (X.T.dot(diff1).dot(X)) - X.T.dot(diff2) - threshold plt2 = plot_implicit(Eq(expr[0, 0], 0), (x, -5, 5), (y, -6, 6)) plt2._backend.ax.scatter(data_0[:, 0], data_0[:, 1], label='data_0') plt2._backend.ax.scatter(data_1[:, 0], data_1[:, 1], label='data_1') plt2._backend.save('plt2.png')
import numpy as np from scipy.stats import beta from sympy import symbols, plot_implicit, Eq, solve, S, solveset n, p = symbols('n p') eq = Eq(n * p * (1 - p)**(n - 1) - 0.05) plt = plot_implicit(eq, x_var=(n, 1, 30), y_var=(p, 0.0001, .9999)) ns = range(15, 17) eps = .01 sols = [solve(Eq(n * p * (1 - p)**(n - 1) - eps), p) for n in ns] ps = [s[1] if len(s) > 1 else s[0] for s in sols] [p * n for p, n in zip(ps, ns)] beta, n, j, k = symbols('beta n j k') eq = beta**(j - n) / (2 + j) * Product(1 - 1 / {1 + k}, (k, n + 1, j)) s = Sum(eq, (j, n + 1, oo)) p = 1 / (1 + n) + s def u(rho): if rho == 1: return lambda c: np.log(c + 1) else: return lambda c: ((c + 1)**(1 - rho) - 1) / (1 - rho) def vq(out, beta): return out / (1 - beta)
# Each ounce of fruit will supply 1 unit of protein, 2 units of carbohydrates, and 1 unit of fat. # Each ounce of nuts will supply 1 unit of protein, 1 unit of carbohydrates, and 1 unit of fat. # Every package must provide at least 5 units of protein, at least 9 units of carbohydrates, and no more than 8 units of fat. # Let x equal the ounces of fruit and y equal the ounces of nuts to be used in each package. # a. Write a system of inequalities to express the conditions of the problem. # b. Graph the feasible region of the system. # https://www.desmos.com/ from sympy import symbols, plot_implicit, plot from sympy.plotting import plot_parametric x_rng = 15 y_rng = 15 x, y = symbols('x, y') exprs = [[x + y >= 5, 'b'], [2 * x + y >= 10, 'r'], [x + y <= 8, 'g']] p = plot_implicit( exprs[ 0 ][ 0 ], ( x, -x_rng, x_rng ), ( y, -y_rng, y_rng ),\ line_color = exprs[ 0 ][ 1 ], show = False ) p.extend( plot_implicit( exprs[ 1 ][ 0 ], ( x, -x_rng, x_rng ), ( y, -y_rng, y_rng ),\ line_color = exprs[ 1 ][ 1 ], show = False ) ) p.extend( plot_implicit( exprs[ 2 ][ 0 ], ( x, -x_rng, x_rng ), ( y, -y_rng, y_rng ),\ line_color = exprs[ 2 ][ 1 ], show = False ) ) p.show()
def test_line_color(): x, y = symbols("x, y") p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False) assert p._series[0].line_color == "green" p = plot_implicit(x**2 + y**2 - 1, line_color="r", show=False) assert p._series[0].line_color == "r"
def test_line_color(): x, y = symbols('x, y') p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False) assert p._series[0].line_color == "green" p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False) assert p._series[0].line_color == "r"
from sympy import symbols, plot_implicit, Eq, plot_parametric from math import sqrt from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from matplotlib import cm x, y, t = symbols('x y t') if True: p = plot_implicit(Eq(y * y + 3 * x * y - x * x * x + 4 * x, 1), (x, -4.6, 7.8), (y, -6.4, 9.4), adaptive=False, depth=1, points=2000, line_color='grey', show=False, xlabel='$x$', ylabel='$y$') p.show() if False: # circle p = plot_implicit(Eq(x * x + y * y, 1), (x, -1.4, 1.4), (y, -1.4, 1.4), adaptive=False, depth=1, points=2000, line_color='grey', show=False, xlabel='', ylabel='', aspect_ratio=(1, 1)) p1 = plot_parametric((1 - 9 * t, 3 * t), show=False) p.append(p1[0])
x_2 - a / 2, x_2 + a / 2, ]) f_2 = sp.Matrix([ x_3 - b / 2, x_3 + b / 2, ]) #aux=list( sp.utilities.iterables.subsets(f,3) ) # combina 2 a 2 #display(psi) p2 = [] for i in f_1: # display(psi.subs({'x_2':sp.solve(i,x_2)[0]}).simplify()) p1 = sp.plot_implicit(sp.Eq(i.subs({a: 2}), 0), (x_2, -4, 4), (x_3, -4, 4)) p2.append(p1) for i in f_2: # display(psi.subs({'x_3':sp.solve(i,x_3)[0]}).simplify()) p1 = sp.plot_implicit(sp.Eq(i.subs({b: 2}), 0), (x_2, -4, 4), (x_3, -4, 4)) p2.append(p1) [p2[0].extend(i) for i in p2] p2[0].show() #%% psi_t = ((2**5) * (a**2) * (b**2)) / (sp.pi**4) * ((-1)**( (k + l) / 2 - 1)) / (k * l * ((k**2 * b**2) + (l**2 * a**2))) * sp.cos( (k * x_2 * sp.pi) / a) * sp.cos((l * x_3 * sp.pi) / b)
def graph(self): warnings.filterwarnings("ignore", category=MatplotlibDeprecationWarning) plot_implicit(self.display_equation.subs(e, E), title="Grafico di " + str(self.display_equation.subs(e, E)))
# -*- coding: utf-8 -*- """ Created on Fri Aug 19 13:57:17 2016 @author: karol """ from sympy import plot_implicit, And, Eq, symbols from sympy.solvers import solve madera, aluminio = symbols('madera aluminio') frm = madera - 6 fra = aluminio - 4 frv = madera*6 + aluminio*8 - 48 fgt = madera*180 + aluminio*90 e1 = Eq(madera - 6, 0) e3 = Eq(madera*6 + aluminio*8 - 48, 0) sol = solve([Eq(frm, 0), Eq(frv, 0)], [madera, aluminio]) val_opt = fgt.subs(sol) plot = plot_implicit(And(frm <= 0, fra <= 0, frv <= 0), (madera, -1, 10), (aluminio, -1, 10), line_color='orange', show=False) plot.extend(plot_implicit(Eq(fgt, val_opt), (madera, -1, 10), (aluminio, -1, 10), line_color='blue', show=False)) plot.show()
def plot_and_save(name): x = Symbol('x') y = Symbol('y') z = Symbol('z') #implicit plot tests plot_implicit(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(Eq(y**2, x**3 - x), (x, -5, 5), (y, -4, 4)).save(tmp_file(name)) plot_implicit(y > 1 / x, (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y < 1 / tan(x), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y >= 2 * sin(x) * cos(x), (x, -5, 5), (y, -2, 2)).save(tmp_file(name)) plot_implicit(y <= x**2, (x, -3, 3), (y, -1, 5)).save(tmp_file(name)) #Test all input args for plot_implicit plot_implicit(Eq(y**2, x**3 - x)).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False).save(tmp_file()) plot_implicit(Eq(y**2, x**3 - x), adaptive=False, points=500).save(tmp_file()) plot_implicit(y > x, (x, -5, 5)).save(tmp_file()) plot_implicit(And(y > exp(x), y > x + 2)).save(tmp_file()) plot_implicit(Or(y > x, y > -x)).save(tmp_file()) plot_implicit(x**2 - 1, (x, -5, 5)).save(tmp_file()) plot_implicit(x**2 - 1).save(tmp_file()) plot_implicit(y > x, depth=-5).save(tmp_file()) plot_implicit(y > x, depth=5).save(tmp_file()) plot_implicit(y > cos(x), adaptive=False).save(tmp_file()) plot_implicit(y < cos(x), adaptive=False).save(tmp_file()) plot_implicit(And(y > cos(x), Or(y > x, Eq(y, x)))).save(tmp_file()) plot_implicit(y - cos(pi / x)).save(tmp_file()) #Test plots which cannot be rendered using the adaptive algorithm #TODO: catch the warning. plot_implicit(Eq(y, re(cos(x) + I*sin(x)))).save(tmp_file(name))
import os from sympy import plot_implicit, symbols, Eq # Instead 'Stars' write your path to exe. file os.system("C:/Users/Lydsyf/PycharmProjects/Mini-Project/bin/Debug/Stars.exe") with open("data.txt", 'r') as f: data = f.readlines() a = [float(i) for i in data[0].split()] x, y = symbols('x y') p = plot_implicit(Eq(a[0] * x**2 + a[1]*x*y + a[2] * y**2 + a[3] * x + a[4] * y + a[5], 0), x_var=(x, -100, 100), y_var=(y, -100, 100), show=False, title='Minimum area ellipse') for i in range(len(data)-1): a = [float(i) for i in data[i+1].split()] p1 = plot_implicit((x - a[0])**2 + (y - a[1])**2 <= 1, x_var=(x, -100, 100), y_var=(y, -100, 100), show=False, line_color='red') p.append(p1[0]) p.show()
# %% N_t theta_t # %% #sp.series(theta_t, x=N, x0=1, n=3) print(sp.latex(sp.series(N_t, x=theta, x0=0, n=5))) # %% x = sp.symbols('x') sp.series(sp.sqrt(1-x), x=x, x0=0, n=4) # %% i = 1.336 g = 2.689e-5 print((i-1)/2/g/i) # %% %matplotlib qt sp.plot_implicit(sp.Eq((index-1)/gamma/index/2, 5000), (index, 1, 2), (gamma, 2e-5, 4e-5)) w
def eqy(x, y): return numpy.sqrt((1 - a * (x ** 2)) / 2) # Вычисление матрицы Якоби def W(x, y): return numpy.array([ [(1 + numpy.tan(x * y + m) ** 2) * y - 1, (1 + numpy.tan(x * y + m) ** 2) * x], [2 * a * x, 4 * y] ]) # Графики исходных уравнений plots = sympy.plot_implicit(sympy.Eq(eq1, 0), (x, -2, 2), (y, -2, 2), line_color="blue", show=False) plots.extend(sympy.plot_implicit(sympy.Eq(eq2, 0), (x, -2, 2), (y, -2, 2), line_color="red", show=False)) # plots.show() iters = 0 def SimpleSolve(x0, y0): global iters iters = 0 (x, y) = (x0, y0) while True: iters += 1 oldx = x oldy = y