I want to graph taylor series in python use matplot
import matplotlib.pyplot as plt
import sympy as sy
import numpy as np
x=sy.Symbol('x')
plt.title("Comparison of EXP(x), PP1, PP2")
plt.xlim(00.1, 3+0.2)
plt.ylim(0, 20+1)
plt.xlabel("x")
plt.ylabel("y: values")
plt.grid(False)
x=np.linspace(0.0, 3.0, 100)
plt.plot(x, np.exp(x), label="exp(x)")
plt.plot(x, np.exp(x).series(x, 0, 4), label="PP1")
plt.legend(loc=2)
plt.show();
I use Jupyter Notebook. I want to graph taylor series of exp(x). I just success to graph exp(x) but failed taylor seires of exp(x). Sympy library has taylor series fuction so I tried it but I don't understand what's the problem. below is the error message and graph.
1 answer

sy.exp(x).series(x)
creates a sympy expression, not a functionyou might want to convert it to a function
from sympy.utilities.lambdify import lambdify x = sy.Symbol('x') exp_expr = sy.exp(x).series(x).removeO() exp_func = lambdify(x, exp_expr)
and plot it out
x_points = np.linspace(0.0, 3.0, 100) plt.plot(x_points, [exp_func(i) for i in x_points])
See also questions close to this topic

how to display contents of text file one line at a time via timer using python on windows?
this is the code.
def wndProc(hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: hdc, paintStruct = win32gui.BeginPaint(hWnd) dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0 fontSize = 36 # http://msdn.microsoft.com/enus/library/windows/desktop/dd145037(v=vs.85).aspx lf = win32gui.LOGFONT() lf.lfFaceName = "Times New Roman" lf.lfHeight = int(round(dpiScale * fontSize)) #lf.lfWeight = 150 # Use nonantialiased to remove the white edges around the text. # lf.lfQuality = win32con.NONANTIALIASED_QUALITY hf = win32gui.CreateFontIndirect(lf) win32gui.SelectObject(hdc, hf) rect = win32gui.GetClientRect(hWnd) # http://msdn.microsoft.com/enus/library/windows/desktop/dd162498(v=vs.85).aspx win32gui.DrawText( hdc, **'Glory be to the Father, and to the son and to the Holy Spirit.',** 1, rect, win32con.DT_CENTER  win32con.DT_NOCLIP  win32con.DT_VCENTER ) win32gui.EndPaint(hWnd, paintStruct) return 0
.where it says the "glory be to the father.." prayer I would like that string to actually display a few different prayers on a timer. what I mean is I want to save short prayers to a text file and have the line where it says "glory be.." to change to a new prayer every 60 seconds cycling through a few prayers such as the serenity prayer etc.

How to plot the frequency of my data per day in an histogram?
I want to plot the number occurences of my data per day. y represent the id of my data. x represent the timestamp which I convert to time and day. But I can't make the correct plot. import matplotlib.pyplot as plt plt.style.use('ggplot') import time
y=['5914cce8fad645d1bec2e59e62823617', '1c2067e051734a1d8a75b18267ee4598', 'db6830fffa9c4aa5b71ef6da9333f357', '672cc9d5360e4451bb7c03e3d0bd8f0d', 'fb0f8122fffc47fea87ab2b749df173b', '558e96ca022240c7acc0e444f7663f53', 'c3f86fd5eac348d3a44cb325f30b6139', '21dd849f895f4cf5a16845a4c1a9fbf9', 'e3b4cd56e291467193b6d2226ee82ae7', '01346c48a8c443d1ac021efa33ca0f4e', '23b78b0f85be4ca799f41a5add76c12e', 'b1c036c00c2b4170a1708fd0add0dec2', '74737546e9c34126bcb24d34503421ca', '342991f5ec874c9d83eb9908f3e221aa', '4fdcd83aeb684e26b79b753c5e022a4e', 'b7fbeca9941643c49e909e71acc1eaba', '27c9d358a3ef4c69ba89eac16d8d3bdb', 'ef982c4ba11548a1aef12f672d7f1f00', 'efedede29bb44c5298b18b03070df3fd', 'eb03ae1b4cde409c8d342a16a8be30d2'] x=['1548143296750', '1548183033872', '1548346185194', '1548443373507', '1548446119319', '1548446239441', '1548446068267', '1548445962159', '1548446011209', '1548446259465', '1548446180380', '1548239985290', '1548240060367', '1548240045347', '1547627568993', '1548755333313', '1548673604016','1548673443843', '1548673503914', '1548673563975'] date=[] for i in x: print(i) print() i=i[:10] print(i) readable = time.ctime(int(i)) readable=readable[:10] date.append(readable) print(date) plt.hist(date,y) plt.show()

mysql.connector.errors.ProgrammingError: Error in SQL Syntax
I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s") cursor.execute(query, (info, shipDate, warranty, name, sn, )) conn.commit()
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.

Replace and Iterate over x and yaxis of multidimensional np.matrix
I have written the following script:
import numpy as np d = 0.05 limits = np.arange(0, 0.5, d) matrix = np.zeros([limits.shape[0], limits.shape[0]]) matrix[:, 0] = limits matrix[0, :] = limits
This gives me the following matrix:
How can I make sure that the values in the first column and first row are the "index"values? So instead of [0,1,2,...,9] there should be [0, 0.05, ...0.45]
Thank you

Concatenate arrays in Python  output error
I am writing a program to concatenate two numpy arrays and I want the program to print a message for each possible outcome (horizontal, vertical, or no concatenation). I have the following code and I donĀ“t understand why even when the first condition (np.hstack) is met it continues evaluating the subsequent if and else statements and wrongly prints that there is both a horizontal concatenation (first condition is met) and that a concatenation is not possible.
import numpy as np def fun1(a,b): if a.shape[0] == b.shape[0]: print("The horizontal concatenation is:", np.hstack((a,b))) if a.shape[1] == b.shape[1]: print("The vertical concatenation is:", np.vstack((a,b))) else: print("These arrays cannot be concatenated.") a = np.floor(10*np.random.random((3,2))) b = np.floor(10*np.random.random((3,4))) fun1(a,b)
Output:
The horizontal concatenation is: [[5. 0. 1. 1. 3. 7.] [4. 1. 8. 3. 1. 9.] [9. 1. 5. 7. 0. 0.]] These arrays cannot be concatenated.

How to merge different timeseries plot into a 2D in Python
I have three different timeseries data of the following format where the first column is timestamp and the second column is the value.
0.086206438,10 0.086425551,12 0.089227066,20 0.089262508,24 0.089744425,30 0.090036815,40 0.090054172,28 0.090377569,28 0.090514071,28 0.090762872,28 0.090912691,27
For reproduciability, I have shared the three timeseries data I am using here.
From column 2, I wanted to read current row and compare it with the value of the previous row. If it is greater, I keep comparing. If the current value is smaller than the previous row's value continue, I take the difference. Let me make it clear. For example in the above sample record I provided, the seventh row (28) is smaller than the value in the sixth row (40)  so it will be (4028 =12).
Here is my sample code.
import numpy as np import pandas as pd import csv import numpy as np import scipy.stats import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from statsmodels.graphics.tsaplots import plot_acf, acf protocols = {} types = {"data1": "data1.csv", "data2": "data2.csv", "data3": "data3.csv"} for protname, fname in types.items(): arr = [] arr1 = [] with open(fname, mode='r', encoding='utf8sig') as f: reader = csv.reader(f, delimiter=",") for i in reader: arr.append(int(i[1])) arr1.append(float(i[0])) arr, arr1 = np.array(arr), np.array(arr1) diffs = np.diff(arr) diffs1 = np.diff(arr1) diffs1 = diffs1[diffs > 0] diffs = diffs[diffs > 0] # To keep only the increased values protocols[protname] = { "rtime": np.array(arr1), "rdata": np.array(arr), "data": diffs, "timediff": diffs, } ## change in time for protname, values in protocols.items(): d = values["rdata"] t = values["rtime"] d = np.diff(d, 1) #/ d[:1] t = np.diff(t, 1) plt.plot(t, d, ".", label=protname, alpha=0.5) plt.xlabel("Changes in time") plt.ylabel("differences") plt.legend() plt.show()
This gives me the following plots
How can we plot the differences versus the change in time (column onw) in a twodimensitional (2D) graph of the three data I included separately?

Matplotlib  Fill_Between doesn't seem work
I'm new to python and learned a ton over the past 2 weeks. I have just started learning and experimenting with matplotlib.pylot. In my code, I have 3 seperate simple graphs on the same plot, in the third graph there are 2 lines. I am trying to have a green fill_between when y2 > y3, and red fill_between when y3 > y2. I have taken a look at other code, and they look identical to mine, but for some reason it doesn't work. Any help?
There are a few commented lines, they are just experimentation.
import matplotlib.pyplot as plt import random from matplotlib import style style.use('fivethirtyeight') def create_points(nPoints): xs = [] ys = [] for i in range(nPoints): rand = random.randrange(0,3*nPoints) xs.append(i) ys.append(rand) return xs, ys x,y = create_points(200) x1,y1 = create_points(200) x2, y2 = create_points(200) x3, y3 = create_points(200) fig = plt.figure() ax1 = plt.subplot2grid((6,1), (0,0), rowspan = 1, colspan = 1) plt.title('Subplot2grid Method') plt.ylabel('Plot 1') ax2 = plt.subplot2grid((6,1), (1,0), rowspan = 4, colspan = 1, sharex = ax1) plt.ylabel('Plot 2') ax2_xtwin = ax2.twinx() ax3 = plt.subplot2grid((6,1), (5,0), rowspan = 1, colspan = 1, sharex = ax1) plt.xlabel('x') plt.ylabel('Plot 3') ax2_xtwin.fill_between(x,0,y, facecolor = '#0079a3', alpha = 0.4) #ax2v.axes.yaxis.set_ticklables([]) ax2_xtwin.grid(False) ax2_xtwin.set_ylim(0, 1.5*max(y)) ax3.plot(x2, y2, x2, y3, linewidth = 1, label = 'x2y2 plot', color = 'k') #ax3.plot(x3, y3, linewidth = 1, label = 'x3y3 plot', color = 'firebrick') ax3.fill_between(x2, y2, y3, where = (y2 >= y3), facecolor = 'darkgreen', edgecolor = 'g', alpha = 0.5, interpolate = True) ax3.fill_between(x2, y2, y3, where = (y2 <= y3), facecolor = 'firebrick', edgecolor = 'r', alpha = 0.5, interpolate = True) #Print Points ax1.plot(x, y, linewidth = 1, label = 'xy plot', color = 'gold') ax2.plot(x1, y1, linewidth = 1, label = 'x1y1 plot', color = 'sandybrown') #ax3.plot(x2, y2, linewidth = 1, label = 'x2y2 plot', color = 'darkgreen') #ax3.plot(x3, y3, linewidth = 1, label = 'x3y3 plot', color = 'firebrick') plt.subplots_adjust(left = 0.15, bottom = 0.1, right = 0.9, top = 0.9, wspace = 0.2, hspace = 0) plt.show()

How to turn a set of data to a matrix and vectors
Suppose I have this huge set of data in a .txt file that has the following structure: first and the second column represents a discrete bidimensional domain, and the third column represents the values calculated on each point of the discrete X and Y axis. Example given below
x y z 1 1 100 1 0 50 1 1 100 0 1 50 0 0 0 0 1 50 1 1 100 0 1 50 1 1 100
It seems stupid, but I've been struggling to turn this data into vectors and matrices like X = [1, 0, 1], Y = [1, 0, 1] and Z = [[100, 50, 100], [50, 0, 50], [100, 50, 100]]. I went through many technics and methods using numpy, but coudn't manage to make it!
As a bonus: would turning this data into vectors and matrices, like I described, be a good way to plot it in a 3dscatter ou 3dcountour type using matplotlib?

Sympy fails to apply Wick theorem for normalordered input
I am learning secondquant module in sympy. I am trying to apply wicks to compute matrix elements. This code runs fine so far:
In [1]: from sympy.physics.secondquant import * In [2]: from sympy import * In [3]: p,q = symbols('p, q') In [4]: pr = NO(Fd(p)*F(q)) In [5]: f = AntiSymmetricTensor('f', (p,), (q,)) In [6]: wicks(f*Fd(p)*F(q)) Out[6]: KroneckerDelta(_i, q)*KroneckerDelta(p, q)*AntiSymmetricTensor(f, (p,), (q,)) + AntiSymmetricTensor(f, (p,), (q,))*NO(CreateFermion(p)*AnnihilateFermion(q))
But if the input contains normalordered products of operators, sympy fails:
In [7]: wicks(f*pr)  SubstitutionOfAmbigousOperatorFailed Traceback (most recent call last) <ipythoninput7776f1333fcce> in <module>() > 1 wicks(f*pr) /usr/lib/python2.7/distpackages/sympy/physics/secondquant.pyc in wicks(e, **kw_args) 2816 2817 # break up any NOobjects, and evaluate commutators > 2818 e = e.doit(wicks=True) 2819 2820 # make sure we have only one term to consider /usr/lib/python2.7/distpackages/sympy/core/basic.pyc in doit(self, **hints) 1517 if hints.get('deep', True): 1518 terms = [term.doit(**hints) if isinstance(term, Basic) else term > 1519 for term in self.args] 1520 return self.func(*terms) 1521 else: /usr/lib/python2.7/distpackages/sympy/physics/secondquant.pyc in doit(self, **kw_args) 1896 """ 1897 if kw_args.get("remove_brackets", True): > 1898 return self._remove_brackets() 1899 else: 1900 return self.__new__(type(self), self.args[0].doit(**kw_args)) /usr/lib/python2.7/distpackages/sympy/physics/secondquant.pyc in _remove_brackets(self) 1934 subslist.append((self[i], split)) 1935 else: > 1936 raise SubstitutionOfAmbigousOperatorFailed(self[i]) 1937 if subslist: 1938 result = NO(self.subs(subslist)) SubstitutionOfAmbigousOperatorFailed: f+(p)
I would expect to produce the input without changes. I would like to use more complicated products of operators in normalordered form, but they fail as well. Am I doing anything wrong?

Python SymPy 1.3 simplify symbolic matrix calculation
I have the following code for a symbolic matrix calculation
from sympy import * A = MatrixSymbol( 'A', 3, 3 ) B = MatrixSymbol( 'B', 3, 3 ) C = MatrixSymbol( 'C', 3, 3 ) Z = A * ( A + B ) * C.inverse() * ( A + B ).transpose() Z.expand()
This gives me the following result
A( A + B ) C^1 ( A^T + B^T )
But I want the expanded result
A * A * C^1 * A^T + A * B C^1 * A^T + A * A C^1 * B^T + A * B C^1 * B^T
Could I ask you guys that how to do it ? Thank you very much

Output of sympy.fourier_transform
I run
sympy.fourier_transform
using the following codefrom sympy import fourier_transform, exp,symbols from sympy.abc import x, k a=fourier_transform(exp(x**2), x, k) s=symbols('s') Ori=(s)*exp((x**2)/(s**2)) FT=fourier_transform(Ori,x,k) a.subs({k:1}).evalf() >>>9.16769605680502e5 FT.subs({s:1,k:1}).evalf() >>>FourierTransform(exp(x**2), x, 1)
a.subs({k:1}).evalf()
is a number, as I was expecting.But I don't understand the result of
FT.subs({s:1,k:1}).evalf()
. It is not a number even though I applied.evalf()
. I want to get a numeric value. What is the problem?Now I'm using sympy version 1.3, python version 3.7.1. This code was running fine with sympy version 1.1.

How to expand in taylor series a composition of functions?
I would like to expand in taylor series a function of type :
f(x+f(x))
aroundx=a
in the case wheref(a)=0
.(%i1) atvalue(f(x),[x=a],0)$
The direct calculus yields :
(%i2) taylor(f(x+f(x)),x,a,2); (%o2)/T/ f(a)+(at('diff(f(f(x)+x),x,1),x=a))*(xa)+((at('diff(f(f(x)+x),x,2),x=a))*(xa)^2)/2+...
If I define a intermediate function :
(%i3)define(tf(x),taylor(f(x),x,a,2))$
Then a expand in Taylor series I get :
(%i4) taylor(f(x+tf(x)),x,a,2); (%o4) 0+...
I expect the following result :
f(1+f'(a))f'(a)(xa)+(xa)^2 f''(a)[f'(a)+(1+f'(a))^2/2]+o(xa)^2
How could I solve this problem?

Why wont this taylorseries give a result for numbers >= 1
I am building my own function for calculating the Cosinus as a Taylorseries. Unfortunately the Code wont execute for numbers > 1. There are many other examples for this problem I know, but for my own javaknowledge I would like to know what is the problem.
public class Cosinus { public static double cos(double x) { double sum = 0.0; for (int i = 0; i <= Double.POSITIVE_INFINITY; i++) { double summand = (Math.pow(x, 2 * i) / fak(2 * i)) * Math.pow((1), i); if (Math.abs(summand) >= 0.001) { sum += summand; } else { break; } } return sum; } private static double fak(int i) { int ergebnis = 1; for (int count = 1; count <= i; count++) { ergebnis = count * ergebnis; } return ergebnis; } public static void main(String[] args) { System.out.println(cos(10.0)); } }

How to do a Taylor expansion of two variables function $f(t,x)$ with symbolic computation
I am looking for a solution to formally compute a taylor development of a bivariate function $f(x,y)$ as does the 'sympy' module of python but for a onevariable function $f(x)$