Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c86fbc7

Browse files
committed
Use np.hypot whereever possible.
Clearer IMO, although perhaps not for the examples?
1 parent 4872b79 commit c86fbc7

31 files changed

+70
-89
lines changed

examples/event_handling/ginput_manual_clabel_sgskip.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def tellme(s):
7171
def f(x, y, pts):
7272
z = np.zeros_like(x)
7373
for p in pts:
74-
z = z + 1/(np.sqrt((x - p[0])**2 + (y - p[1])**2))
74+
z = z + 1 / np.hypot(x - p[0], y - p[1])
7575
return 1/z
7676

7777

examples/event_handling/path_editor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def get_ind_under_point(self, event):
9090
xy = np.asarray(self.pathpatch.get_path().vertices)
9191
xyt = self.pathpatch.get_transform().transform(xy)
9292
xt, yt = xyt[:, 0], xyt[:, 1]
93-
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
93+
d = np.hypot(xt - event.x, yt - event.y)
9494
ind = d.argmin()
9595

9696
if d[ind] >= self.epsilon:

examples/event_handling/pick_event_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def line_picker(line, mouseevent):
123123
xdata = line.get_xdata()
124124
ydata = line.get_ydata()
125125
maxd = 0.05
126-
d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
126+
d = np.hypot(xdata - mouseevent.xdata, ydata - mouseevent.ydata)
127127

128128
ind = np.nonzero(np.less_equal(d, maxd))
129129
if len(ind):

examples/images_contours_and_fields/contourf_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
Z[:nr // 6, :nc // 6] = np.ma.masked
3131

3232
# mask a circle in the middle:
33-
interior = np.sqrt((X**2) + (Y**2)) < 0.5
33+
interior = np.hypot(X, Y) < 0.5
3434
Z[interior] = np.ma.masked
3535

3636
# We are using automatic selection of contour levels;

examples/images_contours_and_fields/image_nonuniform.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
y = np.linspace(-4, 4, 9)
2525

26-
z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2)
26+
z = np.hypot(x[np.newaxis, :], y[:, np.newaxis])
2727

2828
fig, axs = plt.subplots(nrows=2, ncols=2)
2929
fig.subplots_adjust(bottom=0.07, hspace=0.3)

examples/images_contours_and_fields/quadmesh_demo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
X, Y = np.meshgrid(x, y)
2121
Qx = np.cos(Y) - np.cos(X)
2222
Qz = np.sin(Y) + np.sin(X)
23-
Qx = (Qx + 1.1)
24-
Z = np.sqrt(X**2 + Y**2) / 5
25-
Z = (Z - Z.min()) / (Z.max() - Z.min())
23+
Qx = Qx + 1.1
24+
Z = np.hypot(X, Y) / 5
25+
Z = (Z - Z.min()) / Z.ptp()
2626

2727
# The color array can include masked values:
2828
Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)

examples/images_contours_and_fields/tricontour_smooth_delaunay.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@
3636
def experiment_res(x, y):
3737
""" An analytic function representing experiment results """
3838
x = 2. * x
39-
r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
39+
r1 = np.hypot(0.5 - x, 0.5 - y)
4040
theta1 = np.arctan2(0.5 - x, 0.5 - y)
41-
r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
41+
r2 = np.hypot(-x - 0.2, -y - 0.2)
4242
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
4343
z = (4 * (np.exp((r1 / 10)**2) - 1) * 30. * np.cos(3 * theta1) +
4444
(np.exp((r2 / 10)**2) - 1) * 30. * np.cos(5 * theta2) +

examples/images_contours_and_fields/tricontour_smooth_user.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
#-----------------------------------------------------------------------------
1818
def function_z(x, y):
1919
""" A function of 2 variables """
20-
r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
20+
r1 = np.hypot(0.5 - x, 0.5 - y)
2121
theta1 = np.arctan2(0.5 - x, 0.5 - y)
22-
r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
22+
r2 = np.hypot(-x - 0.2, -y - 0.2)
2323
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
2424
z = -(2 * (np.exp((r1 / 10)**2) - 1) * 30. * np.cos(7. * theta1) +
2525
(np.exp((r2 / 10)**2) - 1) * 30. * np.cos(11. * theta2) +

examples/images_contours_and_fields/trigradient_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def dipole_potential(x, y):
6161
tci = CubicTriInterpolator(triang, -V)
6262
# Gradient requested here at the mesh nodes but could be anywhere else:
6363
(Ex, Ey) = tci.gradient(triang.x, triang.y)
64-
E_norm = np.sqrt(Ex**2 + Ey**2)
64+
E_norm = np.hypot(Ex, Ey)
6565

6666
#-----------------------------------------------------------------------------
6767
# Plot the triangulation, the potential iso-contours and the vector field

examples/lines_bars_and_markers/scatter_star_poly.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
x = np.random.rand(10)
1515
y = np.random.rand(10)
16-
z = np.sqrt(x**2 + y**2)
16+
z = np.hypot(x, y)
1717

1818
plt.subplot(321)
1919
plt.scatter(x, y, s=80, c=z, marker=">")

examples/mplot3d/mixed_subplots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def f(t):
3838
X = np.arange(-5, 5, 0.25)
3939
Y = np.arange(-5, 5, 0.25)
4040
X, Y = np.meshgrid(X, Y)
41-
R = np.sqrt(X**2 + Y**2)
41+
R = np.hypot(X, Y)
4242
Z = np.sin(R)
4343

4444
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,

examples/mplot3d/surface3d.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
X = np.arange(-5, 5, 0.25)
2525
Y = np.arange(-5, 5, 0.25)
2626
X, Y = np.meshgrid(X, Y)
27-
R = np.sqrt(X**2 + Y**2)
27+
R = np.sqrt(X, Y)
2828
Z = np.sin(R)
2929

3030
# Plot the surface.

examples/mplot3d/surface3d_3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
Y = np.arange(-5, 5, 0.25)
2323
ylen = len(Y)
2424
X, Y = np.meshgrid(X, Y)
25-
R = np.sqrt(X**2 + Y**2)
25+
R = np.hypot(X, Y)
2626
Z = np.sin(R)
2727

2828
# Create an empty array of strings with the same shape as the meshgrid, and

examples/mplot3d/trisurf3d_2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
# Mask off unwanted triangles.
7070
xmid = x[triang.triangles].mean(axis=1)
7171
ymid = y[triang.triangles].mean(axis=1)
72-
mask = np.where(xmid**2 + ymid**2 < min_radius**2, 1, 0)
72+
mask = np.hypot(xmid, ymid) < min_radius
7373
triang.set_mask(mask)
7474

7575
# Plot the surface.

examples/mplot3d/voxels_torus.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def midpoints(x):
2727
rc, thetac, zc = midpoints(r), midpoints(theta), midpoints(z)
2828

2929
# define a wobbly torus about [0.7, *, 0]
30-
sphere = (rc - 0.7)**2 + (zc + 0.2*np.cos(thetac*2))**2 < 0.2**2
30+
sphere = np.hypot(rc - 0.7, zc + 0.2*np.cos(thetac*2)) < 0.2
3131

3232
# combine the color components
3333
hsv = np.zeros(sphere.shape + (3,))

examples/mplot3d/wire3d_animation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def generate(X, Y, phi):
1818
'''
1919
Generates Z data for the points in the X, Y meshgrid and parameter phi.
2020
'''
21-
R = 1 - np.sqrt(X**2 + Y**2)
21+
R = 1 - np.hypot(X, Y)
2222
return np.cos(2 * np.pi * X + phi) * R
2323

2424

lib/matplotlib/bezier.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,11 +291,9 @@ def split_path_inout(path, inside, tolerence=0.01, reorder_inout=False):
291291

292292

293293
def inside_circle(cx, cy, r):
294-
r2 = r ** 2
295-
296294
def _f(xy):
297295
x, y = xy
298-
return (x - cx) ** 2 + (y - cy) ** 2 < r2
296+
return np.hypot(x - cx, y - cy) < r
299297
return _f
300298

301299

lib/matplotlib/contour.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -230,11 +230,7 @@ def print_label(self, linecontour, labelwidth):
230230

231231
def too_close(self, x, y, lw):
232232
"Return *True* if a label is already near this location."
233-
for loc in self.labelXYs:
234-
d = np.sqrt((x - loc[0]) ** 2 + (y - loc[1]) ** 2)
235-
if d < 1.2 * lw:
236-
return True
237-
return False
233+
return any(np.hypot(x - loc[0], y - loc[1]) < 1.2 * lw for loc in self.labelXYs)
238234

239235
def get_label_coords(self, distances, XX, YY, ysize, lw):
240236
"""

lib/matplotlib/lines.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def segment_hits(cx, cy, x, y, radius):
8181
"""
8282
# Process single points specially
8383
if len(x) < 2:
84-
res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
84+
res, = np.nonzero(np.hypot(cx - x, cy - y) <= radius)
8585
return res
8686

8787
# We need to lop the last element off a lot.
@@ -93,25 +93,21 @@ def segment_hits(cx, cy, x, y, radius):
9393
Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
9494
u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
9595
candidates = (u >= 0) & (u <= 1)
96-
#if any(candidates): print "candidates",xr[candidates]
9796

9897
# Note that there is a little area near one side of each point
9998
# which will be near neither segment, and another which will
10099
# be near both, depending on the angle of the lines. The
101100
# following radius test eliminates these ambiguities.
102-
point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
103-
#if any(point_hits): print "points",xr[candidates]
101+
points_hit = np.hypot(cx - x, cy - y) <= radius
104102
candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
105103

106104
# For those candidates which remain, determine how far they lie away
107105
# from the line.
108106
px, py = xr + u * dx, yr + u * dy
109-
line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
110-
#if any(line_hits): print "lines",xr[candidates]
107+
line_hits = np.hypot(cx - px, cy - py) <= radius
111108
line_hits = line_hits & candidates
112109
points, = point_hits.ravel().nonzero()
113110
lines, = line_hits.ravel().nonzero()
114-
#print points,lines
115111
return np.concatenate((points, lines))
116112

117113

@@ -484,17 +480,15 @@ def contains(self, mouseevent):
484480
else:
485481
pixels = self.figure.dpi / 72. * self.pickradius
486482

487-
# the math involved in checking for containment (here and inside of
488-
# segment_hits) assumes that it is OK to overflow. In case the
489-
# application has set the error flags such that an exception is raised
490-
# on overflow, we temporarily set the appropriate error flags here and
491-
# set them back when we are finished.
483+
# The math involved in checking for containment (here and inside of
484+
# segment_hits) assumes that it is OK to overflow, so temporarily set
485+
# the error flags accordingly.
492486
with np.errstate(all='ignore'):
493487
# Check for collision
494488
if self._linestyle in ['None', None]:
495489
# If no line, return the nearby point(s)
496-
d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
497-
ind, = np.nonzero(np.less_equal(d, pixels ** 2))
490+
ind, = np.nonzero(
491+
np.hypot(xt - mouseevent.x, yt - mouseevent.y) <= pixels)
498492
else:
499493
# If line, return the nearby segment(s)
500494
ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)

lib/matplotlib/patches.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,10 +1363,8 @@ def get_path(self):
13631363
xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1)
13641364

13651365
# a point on the segment 20% of the distance from the tip to the base
1366-
theta = math.atan2(y2 - y1, x2 - x1)
1367-
r = math.sqrt((y2 - y1) ** 2. + (x2 - x1) ** 2.)
1368-
xm = x1 + self.frac * r * math.cos(theta)
1369-
ym = y1 + self.frac * r * math.sin(theta)
1366+
xm = x1 + self.frac * (x2 - x1)
1367+
ym = y1 + self.frac * (y2 - y1)
13701368
xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1)
13711369
xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2)
13721370

@@ -2950,10 +2948,10 @@ def connect(self, posA, posB):
29502948
codes.append(Path.LINETO)
29512949
else:
29522950
dx1, dy1 = x1 - cx, y1 - cy
2953-
d1 = (dx1 ** 2 + dy1 ** 2) ** .5
2951+
d1 = np.hypot(dx1, dy1)
29542952
f1 = self.rad / d1
29552953
dx2, dy2 = x2 - cx, y2 - cy
2956-
d2 = (dx2 ** 2 + dy2 ** 2) ** .5
2954+
d2 = np.hypot(dx2, dy2)
29572955
f2 = self.rad / d2
29582956
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
29592957
(cx, cy),
@@ -3355,7 +3353,7 @@ def transmute(self, path, mutation_size, linewidth):
33553353

33563354
head_length = self.head_length * mutation_size
33573355
head_width = self.head_width * mutation_size
3358-
head_dist = math.sqrt(head_length ** 2 + head_width ** 2)
3356+
head_dist = np.hypot(head_length, head_width)
33593357
cos_t, sin_t = head_length / head_dist, head_width / head_dist
33603358

33613359
# begin arrow

lib/matplotlib/projections/geo.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -470,15 +470,12 @@ def transform_non_affine(self, ll):
470470
diff_long = longitude - clong
471471
cos_diff_long = np.cos(diff_long)
472472

473-
inner_k = (1.0 +
474-
np.sin(clat)*sin_lat +
475-
np.cos(clat)*cos_lat*cos_diff_long)
476-
# Prevent divide-by-zero problems
477-
inner_k = np.where(inner_k == 0.0, 1e-15, inner_k)
478-
k = np.sqrt(2.0 / inner_k)
479-
x = k*cos_lat*np.sin(diff_long)
480-
y = k*(np.cos(clat)*sin_lat -
481-
np.sin(clat)*cos_lat*cos_diff_long)
473+
inner_k = np.max( # Prevent divide-by-zero problems
474+
1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,
475+
1e-15)
476+
k = np.sqrt(2 / inner_k)
477+
x = k * cos_lat*np.sin(diff_long)
478+
y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)
482479

483480
return np.concatenate((x, y), 1)
484481
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
@@ -502,8 +499,7 @@ def transform_non_affine(self, xy):
502499
y = xy[:, 1:2]
503500
clong = self._center_longitude
504501
clat = self._center_latitude
505-
p = np.sqrt(x*x + y*y)
506-
p = np.where(p == 0.0, 1e-9, p)
502+
p = np.max(np.hypot(x, y), 1e-9)
507503
c = 2.0 * np.arcsin(0.5 * p)
508504
sin_c = np.sin(c)
509505
cos_c = np.cos(c)

lib/matplotlib/streamplot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
194194
streamlines.extend(np.hstack([points[:-1], points[1:]]))
195195

196196
# Add arrows half way along each trajectory.
197-
s = np.cumsum(np.sqrt(np.diff(tx) ** 2 + np.diff(ty) ** 2))
197+
s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
198198
n = np.searchsorted(s, s[-1] / 2.)
199199
arrow_tail = (tx[n], ty[n])
200200
arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
@@ -420,7 +420,7 @@ def get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
420420
# speed (path length) will be in axes-coordinates
421421
u_ax = u / dmap.grid.nx
422422
v_ax = v / dmap.grid.ny
423-
speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
423+
speed = np.ma.hypot(u_ax, v_ax)
424424

425425
def forward_time(xi, yi):
426426
ds_dt = interpgrid(speed, xi, yi)
@@ -543,7 +543,7 @@ def _integrate_rk12(x0, y0, dmap, f, maxlength):
543543

544544
nx, ny = dmap.grid.shape
545545
# Error is normalized to the axes coordinates
546-
error = np.sqrt(((dx2 - dx1) / nx) ** 2 + ((dy2 - dy1) / ny) ** 2)
546+
error = np.hypot((dx2 - dx1) / nx, (dy2 - dy1) / ny)
547547

548548
# Only save step if within error tolerance
549549
if error < maxerror:

lib/matplotlib/tests/test_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1183,7 +1183,7 @@ def test_pcolorargs():
11831183
x = np.linspace(-1.5, 1.5, n)
11841184
y = np.linspace(-1.5, 1.5, n*2)
11851185
X, Y = np.meshgrid(x, y)
1186-
Z = np.sqrt(X**2 + Y**2)/5
1186+
Z = np.hypot(X, Y) / 5
11871187

11881188
_, ax = plt.subplots()
11891189
with pytest.raises(TypeError):

lib/matplotlib/tests/test_contour.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def test_circular_contour_warning():
360360
# Check that almost circular contours don't throw a warning
361361
with pytest.warns(None) as record:
362362
x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
363-
r = np.sqrt(x ** 2 + y ** 2)
363+
r = np.hypot(x, y)
364364

365365
plt.figure()
366366
cs = plt.contour(x, y, r)

lib/matplotlib/tests/test_image.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -760,12 +760,11 @@ def test_mask_image():
760760
def test_imshow_endianess():
761761
x = np.arange(10)
762762
X, Y = np.meshgrid(x, x)
763-
Z = ((X-5)**2 + (Y-5)**2)**0.5
763+
Z = np.hypot(X - 5, Y - 5)
764764

765765
fig, (ax1, ax2) = plt.subplots(1, 2)
766766

767-
kwargs = dict(origin="lower", interpolation='nearest',
768-
cmap='viridis')
767+
kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')
769768

770769
ax1.imshow(Z.astype('<f8'), **kwargs)
771770
ax2.imshow(Z.astype('>f8'), **kwargs)

0 commit comments

Comments
 (0)