English 中文(简体)
为什么我在R2中的渐进计算与分析梯度计算不相符?
原标题:Why my np.gradient calculation in R^2 doesn t fit with the analytical gradient calculation?
我试图用 np. gradient 来计算地图上的梯度, 但我遇到了问题。 为了简化我的问题 。 为了简化我的问题, 我正尝试分析函数 z = f( x, y) = - (x - 2) ** 2 np. 梯度没有提供预期结果; 矢量应该指向中心 。 我做错了什么? 这是我正在运行的代码 : 导入 np 以导入 matplotlib. ppplot 作为 plt # 定义 x 和 y = np. linspace ( 4, 4, 50) * * 0 和 y = n. linspace ( 4, 4, 4, 100) # 100 点 在 0 和 4 X, Y = n. mshgrid (x, y) # 创建 2D 网点 # 定义函数 f(x, y) = - (X) Q =- (x, (x) a. dz_ dread, driot, d.
最佳回答
the problem is not in the gradient function, it is in the different indexing order of np.meshgrid and np.gradient. by default np.gradient assumes the indexing is the same order as the arguments, ie: Z[x,y] -> np.gradient(Z, x, y) whereas np.meshgrid default indexing results in the opposite indexing, Z[y,x] -> np.meshgrid(x,y) # default indexing = xy you didn t notice this bug because both X and Y are identical, if you made X and Y have different number of points you would get an error. I like to use Z[y,x], so just swap the order of arguments and return of np.gradient and you will get the correct result. dz_dy, dz_dx = np.gradient(Z, y, x) # Z[y,x]
问题回答
I m not sure why np.gradient is not working as your expect it, but you could instead manually calculate the gradients, e.g., import numpy as np import matplotlib.pyplot as plt # Define the grids for x and y x = np.linspace(0, 4, 100) # 100 points between 0 and 4 y = np.linspace(0, 4, 100) # 100 points between 0 and 4 X, Y = np.meshgrid(x, y) # Create a 2D grid # Define the function f(x, y) def func(X, Y): return -(X - 2)**2 - (Y - 2)**2 def grad(func, X, Y, delta=0.01): """ Calculate gradients of a function. """ dp = delta / 2 df_dx = (func(X + dp, Y) - func(X - dp, Y)) / delta df_dy = (func(X, Y + dp) - func(X, Y - dp)) / delta return df_dx, df_dy Z = func(X, Y) dz_dx, dz_dy = grad(func, X, Y) # Downsampling to reduce the density of arrows step = 10 start = step // 2 plt.figure(figsize=(10, 8)) contour = plt.contourf(X, Y, Z, cmap= viridis , levels=50, alpha=0.8) plt.colorbar(contour, label= f(x, y) ) plt.quiver(X[start::step, start::step], Y[start::step, start::step], dz_dx[start::step, start::step], dz_dy[start::step, start::step], color= r , headlength=3, headwidth=4) plt.title( Function $f(x, y) = -(x - 2)^2 - (y - 2)^2$ and its gradients (numerical) ) plt.xlabel( x ) plt.ylabel( y ) plt.grid(True) plt.show()
As Ahmed AEK explained in their answer, the issue is with the orderings. Rather than changing how you call np.gradient, you should change how you call np.meshgrid. If you look at the np.meshgrid documentation, you ll see that by default indexing="xy". The other option is indexing="ij". This controls how the points in the meshgrid are defined/ordered. For "xy" ordering, you can imagine the array as a cartesian coordinate plane. The bottom left is (0,0), the x value increases as you move right and the y value increases as you move up. For "ij" ordering, the indexing is like the coordinates of a cartesian plane. Meaning, (0,0) when used as an array index is the top left, increasing the x value would mean increasing the first value in the array index, so moving down (going row-by-row) increases the x value. The second index is the y "coordinate", so moving across (column-by-column) increases the y value. So, all you need to do is change your meshgrid call to: X, Y = np.meshgrid(x, y, indexing="ij")




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签