Python has some nice features in creating functions. You can create default values for variables, have optional variables and optional keyword variables.In this function f(a,b), a and b are called positional arguments, and they are required, and must be provided in the same order as the function defines.If we provide a default value for an argument, then the argument is called a keyword argument, and it becomes optional. You can combine positional arguments and keyword arguments, but positional arguments must come first. Here is an example.
Def func(a, n=2):'compute the nth power of a' return a.n# three different ways to call the function print(func(2))print(func(2, 3))print(func(2, n=4))4816In the first call to the function, we only define the argument a, which is a mandatory, positional argument. In the second call, we define a and n, in the order they are defined in the function. Finally, in the third call, we define a as a positional argument, and n as a keyword argument.If all of the arguments are optional, we can even call the function with no arguments. If you give arguments as positional arguments, they are used in the order defined in the function. If you use keyword arguments, the order is arbitrary. Def func(a=1, n=2):'compute the nth power of a' return a.n# three different ways to call the function print(func)print(func(2, 4))print(func(n=4, a=2))11616It is occasionally useful to allow an arbitrary number of arguments in a function.
Subject: SciPy-User SciPy-user ValueError: arrays must have same number of dimensions Hi I am trying to translate a Matlab code from Trefethen's Spectral Methods in MATLAB to Python. I am running into a problem with numpy.concatenate wanting the arrays to have the same number of dimensions.
Suppose we want a function that can take an arbitrary number of positional arguments and return the sum of all the arguments. We use the syntax.args to indicate arbitrary positional arguments.
Inside the function the variable args is a tuple containing all of the arguments passed to the function. Import numpy as npa = np.array(1, 2, 3)b = np.array(4, 5, 6)print(np.rowstack(a, b))# this means stack the arrays vertically, e.g. On top of each other print(np.vstack(a, b))1 2 34 5 61 2 34 5 6The opposite operation is to extract the rows or columns of a 2D array into smaller arrays. We might want to do that to extract a row or column from a calculation for further analysis, or plotting for example. There are splitting functions in numpy. They are somewhat confusing, so we examine some examples. The numpy.hsplit command splits an array 'horizontally'.
The best way to think about it is that the 'splits' move horizontally across the array. In other words, you draw a vertical split, move over horizontally, draw another vertical split, etc You must specify the number of splits that you want, and the array must be evenly divisible by the number of splits. Import numpy as npA = np.array(1, 2, 3, 5,4, 5, 6, 9)# split into two parts p1, p2, p3, p4 = A.Tprint(p1)print(p2)print(p3)print(p4)print(p4.shape)1 42 53 65 9(2,)Note that now, we have 1D arrays.You can also access rows and columns by indexing.
We index an array by row, column. To get a row, we specify the row number, and all the columns in that row like this row,:. Similarly, to get a column, we specify that we want all rows in that column like this: :, column.
This approach is useful when you only want a few columns or rows. Print(x1: 4) # second to fourth element. Element 5 is not included print(x0: -1:2) # every other element print(x:) # print the whole vector print(x-1:0:-1) # reverse the vector!-2.44346095 -1.74532925 -1.04719755-3.14159265 -1.74532925 -0.34906585 1.04719755 2.44346095-3.14159265 -2.44346095 -1.74532925 -1.04719755 -0.34906585 0.34909755 1.74532925 2.44346095 3.14159265 3.14159265 2.44346095 1.74532925 1.04719755 0.34906585 -0.34906585-1.04719755 -1.74532925 -2.44346095Suppose we want the part of the vector where x 2.
We could do that by inspection, but there is a better way. We can create a mask of boolean (0 or 1) values that specify whether x 2 or not, and then use the mask as an index. Numpy has a function called numpy.diff that is similar to the one found in matlab. It calculates the differences between the elements in your list, and returns a list that is one element shorter, which makes it unsuitable for plotting the derivative of a function.Loops in python are pretty slow (relatively speaking) but they are usually trivial to understand. In this script we show some simple ways to construct derivative vectors using loops.
It is implied in these formulas that the data points are equally spaced. If they are not evenly spaced, you need a different approach. Import numpy as npfrom pylab import.import time' These are the brainless way to calculate numerical derivatives. They work well for very smooth data. They are surprisingly fast even up to 10000 points in the vector. ' x = np.linspace(0.78,0.79,100)y = np.sin(x)dyanalytical = np.cos(x)' lets use a forward difference method: that works up until the last point, where there is not a forward difference to use. There, we use a backward difference.
Import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0, 2. np.pi, 100)y = np.sin(x)dyanalytical = np.cos(x)# we need to specify the size of dy ahead because diff returns # an array of n-1 elements dy = np.zeros(y.shape, np. Float) # we know it will be this size dy0:-1 = np.diff(y) / np.diff(x)dy-1 = (y-1 - y-2) / (x-1 - x-2)' calculate dy by center differencing using array slices ' dy2 = np.zeros(y.shape,np. Float) # we know it will be this size dy21:-1 = (y2: - y0:-2) / (x2: - x0:-2)# now the end points dy20 = (y1 - y0) / (x1 - x0)dy2-1 = (y-1 - y-2) / (x-1 - x-2)plt.plot(x,y)plt.plot(x,dyanalytical,label= 'analytical derivative')plt.plot(x,dy,label= 'forward diff')plt.plot(x,dy2, 'k-',lw=2,label= 'centered diff')plt.legend(loc= 'lower left')plt.savefig( 'images/vectorized-diffs.png').
You can see a third order polynomial is a reasonable fit here. There are only 6 data points here, so any higher order risks overfitting. Here is the comparison of the numerical derivative and the fitted derivative. We have 'resampled' the fitted derivative to show the actual shape. Note the derivative appears to go through a maximum near t = 0.9. In this case, that is probably unphysical as the data is related to the consumption of species A in a reaction. The derivative should increase monotonically to zero.
The increase is an artefact of the fitting process. End points are especially sensitive to this kind of error. Import numpy as npimport matplotlib.pyplot as pltN = 101 # number of points L = 2. np.pi # interval of data x = np.arange(0.0, L, L/ float(N)) # this does not include the endpoint # add some random noise y = np.sin(x) + 0.05. np.random.random(size=x.shape)dyanalytical = np.cos(x)' you can use fft to calculate derivatives!
' if N% 2 0:k = np.asarray( list( range(0, N // 2)) + 0 + list( range(-N // 2 + 1, 0)), np.float64)else:k = np.asarray( list( range(0, (N - 1) // 2)) + 0 + list( range(-(N - 1) // 2, 0)), np.float64)k.= 2. np.pi / Lfd = np.real(np.fft.ifft(1.0j. k.
np.fft.fft(y)))plt.plot(x, y, label= 'function')plt.plot(x,dyanalytical,label= 'analytical der')plt.plot(x,fd,label= 'fft der')plt.legend(loc= 'lower left')plt.savefig( 'images/fft-der.png')plt.show. Def f1(x):if x = 0) & (x = 1) & (x.
I am trying to fit a linear line of best fit to my matplotlib graph. I keep getting the error that x and y do not have the same first dimension. But they both have lengths of 15. What am I doing wrong?