Mathematica Asked on March 6, 2021
I want to replicate with Mathematica the following plot (obtained with matplotlib.pyplot module in Python) concering the so-called Rosenbrock function
Here is my effort in Mathematica
f[x_, y_] := (1 - x)^2 + 100 (y - x^2)^2
ContourPlot[f[x, y], {x, -0.5, 2}, {y, -1.5, 4}, Contours -> 20,
ContourShading -> None,
PlotLabel -> "Rosenbrock function" <> ToString[f[x, y]],
FormatType -> TraditionalForm]
which produces
How should I modify the PlotLabel
in order to appear properly (In fact, is it possible the math text to be LaTeX mathematical formulas?)
The function values descend towards a banana-shaped valley, which itself decreases slowly towards the function’s global minimum at (1, 1). How can I make Mathematica to depict this? (Compare the two figures.)
(EDIT)
I add for reference the Python script
import numpy as np
import matplotlib.pyplot as plt
#Plot of Rosenbrock's banana function: f(x,y)=(1-x)^2+100(y-x^2)^2
rosenbrockfunction = lambda x,y: (1-x)**2+100*(y-x**2)**2
n = 100 # number of discretization points along the x-axis
m = 100 # number of discretization points along the x-axis
a=-0.5; b=2. # extreme points in the x-axis
c=-1.5; d=4. # extreme points in the y-axis
X,Y = np.meshgrid(np.linspace(a,b,n), np.linspace(c,d,m))
Z = rosenbrockfunction(X,Y)
plt.contour(X,Y,Z,np.logspace(-0.5,3.5,20,base=10),cmap='gray')
plt.title(r'$textrm{Rosenbrock Function: } f(x,y)=(1-x)^2+100(y-x^2)^2$')
plt.xlabel('x')
plt.ylabel('y')
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.show()
How should I modify the
PlotLabel
in order to appear properly?
PlotLabel -> Row[{"Rosenbrock function ", f[x, y]}]
(In fact, is it possible the math text to be LaTeX mathematical formulas?)
MaTeX[f[x, y]]
MaTeX["text{Rosebrock function: $" <> ToString@TeXForm[f[x, y]] <> "$}"]
The function values descend towards a banana-shaped valley, which itself decreases slowly towards the function’s global minimum at (1, 1). How can I make Mathematica to depict this? (Compare the two figures.)
Mathematica uses contours that correspond to equi-spaced function values. To make the contours denser (instead of less dense) towards the minimum, you either need to explicitly set a list of Contours
, or use a monotonic transformation on the function values. Power functions are often useful for this. Since this function is built from squares, a power of 0.5
makes the contours appears approximately equi-spaced on the plot plane. A value smaller than this makes them denser around the minimum.
ContourPlot[
f[x, y]^0.33, {x, -0.5, 2}, {y, -1.5, 4},
Contours -> 30, PlotPoints -> 60,
ContourShading -> None,
PlotLabel -> Row[{"Rosenbrock function ", f[x, y]}]
]
Correct answer by Szabolcs on March 6, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP