Skip to content

Commit 3ea6cfa

Browse files
committed
Remove unnecessary calls to float() before division.
Most of these calls probably date back to the time before `__future__`-division existed... Note that this will have the side effect that some functions that were accidentally accepting strings instead of floats before will no longer accept strings -- which seems fine to me.
1 parent b2a9e10 commit 3ea6cfa

30 files changed

+76
-85
lines changed

examples/api/mathtext_asarray.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
r'some other string', color='red', fontsize=20, dpi=200)
2323

2424
fig = plt.figure()
25-
fig.figimage(rgba1.astype(float)/255., 100, 100)
26-
fig.figimage(rgba2.astype(float)/255., 100, 300)
25+
fig.figimage(rgba1, 100, 100)
26+
fig.figimage(rgba2, 100, 300)
2727

2828
plt.show()

examples/color/color_cycle_default.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
colors = prop_cycle.by_key()['color']
1414

1515
lwbase = plt.rcParams['lines.linewidth']
16-
thin = float('%.1f' % (lwbase / 2))
16+
thin = lwbase / 2
1717
thick = lwbase * 3
1818

1919
fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
@@ -29,7 +29,7 @@
2929

3030
axs[1, icol].set_facecolor('k')
3131
axs[1, icol].xaxis.set_ticks(np.arange(0, 10, 2))
32-
axs[0, icol].set_title('line widths (pts): %.1f, %.1f' % (lwx, lwy),
32+
axs[0, icol].set_title('line widths (pts): %g, %g' % (lwx, lwy),
3333
fontsize='medium')
3434

3535
for irow in range(2):

examples/lines_bars_and_markers/stackplot_demo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def bump(a):
4343
y = 2 * np.random.random() - .5
4444
z = 10 / (.1 + np.random.random())
4545
for i in range(m):
46-
w = (i / float(m) - y) * z
46+
w = (i / m - y) * z
4747
a[i] += x * np.exp(-w * w)
4848
a = np.zeros((m, n))
4949
for i in range(n):

examples/statistics/hist.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
N, bins, patches = axs[0].hist(x, bins=n_bins)
5353

5454
# We'll color code by height, but you could use any scalar
55-
fracs = N.astype(float) / N.max()
55+
fracs = N / N.max()
5656

5757
# we need to normalize the data to 0..1 for the full range of the colormap
5858
norm = colors.Normalize(fracs.min(), fracs.max())

lib/matplotlib/axes/_axes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6490,7 +6490,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
64906490
if stacked and density:
64916491
db = np.diff(bins)
64926492
for m in tops:
6493-
m[:] = (m.astype(float) / db) / tops[-1].sum()
6493+
m[:] = (m / db) / tops[-1].sum()
64946494
if cumulative:
64956495
slc = slice(None)
64966496
if cbook.is_numlike(cumulative) and cumulative < 0:

lib/matplotlib/backends/backend_agg.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def draw_path(self, gc, path, transform, rgbFace=None):
146146

147147
if (nmax > 100 and npts > nmax and path.should_simplify and
148148
rgbFace is None and gc.get_hatch() is None):
149-
nch = np.ceil(npts / float(nmax))
149+
nch = np.ceil(npts / nmax)
150150
chsize = int(np.ceil(npts / nch))
151151
i0 = np.arange(0, npts, chsize)
152152
i1 = np.zeros_like(i0)

lib/matplotlib/backends/backend_mixed.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ def stop_rasterizing(self):
139139
# backends support this.
140140
self._renderer.draw_image(
141141
gc,
142-
float(l) / self.dpi * self._figdpi,
143-
(float(height)-b-h) / self.dpi * self._figdpi,
142+
l * self._figdpi / self.dpi,
143+
(height-b-h) * self._figdpi / self.dpi,
144144
image)
145145
self._raster_renderer = None
146146
self._rasterizing = False

lib/matplotlib/backends/backend_pdf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1282,7 +1282,7 @@ def writeGouraudTriangles(self):
12821282
flat_colors = colors.reshape((shape[0] * shape[1], 4))
12831283
points_min = np.min(flat_points, axis=0) - (1 << 8)
12841284
points_max = np.max(flat_points, axis=0) + (1 << 8)
1285-
factor = float(0xffffffff) / (points_max - points_min)
1285+
factor = 0xffffffff / (points_max - points_min)
12861286

12871287
self.beginStream(
12881288
ob.id, None,

lib/matplotlib/backends/backend_ps.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -800,7 +800,7 @@ def draw_gouraud_triangles(self, gc, points, colors, trans):
800800
flat_colors = colors.reshape((shape[0] * shape[1], 4))
801801
points_min = np.min(flat_points, axis=0) - (1 << 12)
802802
points_max = np.max(flat_points, axis=0) + (1 << 12)
803-
factor = np.ceil(float(2 ** 32 - 1) / (points_max - points_min))
803+
factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
804804

805805
xmin, ymin = points_min
806806
xmax, ymax = points_max

lib/matplotlib/backends/backend_wx.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,7 @@ def _onMouseWheel(self, evt):
10991099
delta = evt.GetWheelDelta()
11001100
rotation = evt.GetWheelRotation()
11011101
rate = evt.GetLinesPerAction()
1102-
step = rate * float(rotation) / delta
1102+
step = rate * rotation / delta
11031103

11041104
# Done handling event
11051105
evt.Skip()

lib/matplotlib/colors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1315,7 +1315,7 @@ def __call__(self, value, clip=None):
13151315
for i, b in enumerate(self.boundaries):
13161316
iret[xx >= b] = i
13171317
if self._interp:
1318-
scalefac = float(self.Ncmap - 1) / (self.N - 2)
1318+
scalefac = (self.Ncmap - 1) / (self.N - 2)
13191319
iret = (iret * scalefac).astype(np.int16)
13201320
iret[xx < self.vmin] = -1
13211321
iret[xx >= self.vmax] = max_col

lib/matplotlib/contour.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1563,8 +1563,8 @@ def _initialize_x_y(self, z):
15631563
x0, x1, y0, y1 = (0, Nx, 0, Ny)
15641564
else:
15651565
x0, x1, y0, y1 = self.extent
1566-
dx = float(x1 - x0) / Nx
1567-
dy = float(y1 - y0) / Ny
1566+
dx = (x1 - x0) / Nx
1567+
dy = (y1 - y0) / Ny
15681568
x = x0 + (np.arange(Nx) + 0.5) * dx
15691569
y = y0 + (np.arange(Ny) + 0.5) * dy
15701570
if self.origin == 'upper':

lib/matplotlib/dates.py

+12-14
Original file line numberDiff line numberDiff line change
@@ -306,23 +306,21 @@ def _from_ordinalf(x, tz=None):
306306
if tz is None:
307307
tz = _get_rc_timezone()
308308

309-
ix = int(x)
309+
ix, remainder = divmod(x, 1)
310+
ix = int(ix)
310311
if ix < 1:
311-
raise ValueError('cannot convert {} to a date. This '
312-
'often happens if non-datetime values are passed to '
313-
'an axis that expects datetime objects. '
314-
.format(ix))
312+
raise ValueError('Cannot convert {} to a date. This often happens if '
313+
'non-datetime values are passed to an axis that '
314+
'expects datetime objects.'.format(ix))
315315
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
316316

317-
remainder = float(x) - ix
318-
319317
# Since the input date `x` float is unable to preserve microsecond
320318
# precision of time representation in non-antique years, the
321319
# resulting datetime is rounded to the nearest multiple of
322320
# `musec_prec`. A value of 20 is appropriate for current dates.
323321
musec_prec = 20
324-
remainder_musec = int(round(remainder * MUSECONDS_PER_DAY /
325-
float(musec_prec)) * musec_prec)
322+
remainder_musec = int(round(remainder * MUSECONDS_PER_DAY / musec_prec)
323+
* musec_prec)
326324

327325
# For people trying to plot with full microsecond precision, enable
328326
# an early-year workaround
@@ -1287,10 +1285,10 @@ def get_locator(self, dmin, dmax):
12871285
# these similar functions, and it's best to avoid doing our own math
12881286
# whenever possible.
12891287
numYears = float(delta.years)
1290-
numMonths = (numYears * MONTHS_PER_YEAR) + delta.months
1288+
numMonths = numYears * MONTHS_PER_YEAR + delta.months
12911289
numDays = tdelta.days # Avoids estimates of days/month, days/year
1292-
numHours = (numDays * HOURS_PER_DAY) + delta.hours
1293-
numMinutes = (numHours * MIN_PER_HOUR) + delta.minutes
1290+
numHours = numDays * HOURS_PER_DAY + delta.hours
1291+
numMinutes = numHours * MIN_PER_HOUR + delta.minutes
12941292
numSeconds = np.floor(tdelta.total_seconds())
12951293
numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
12961294

@@ -1745,14 +1743,14 @@ def seconds(s):
17451743
"""
17461744
Return seconds as days.
17471745
"""
1748-
return float(s) / SEC_PER_DAY
1746+
return s / SEC_PER_DAY
17491747

17501748

17511749
def minutes(m):
17521750
"""
17531751
Return minutes as days.
17541752
"""
1755-
return float(m) / MINUTES_PER_DAY
1753+
return m / MINUTES_PER_DAY
17561754

17571755

17581756
def hours(h):

lib/matplotlib/figure.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,7 @@ def figimage(self, X,
726726

727727
if resize:
728728
dpi = self.get_dpi()
729-
figsize = [x / float(dpi) for x in (X.shape[1], X.shape[0])]
729+
figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
730730
self.set_size_inches(figsize, forward=True)
731731

732732
im = FigureImage(self, cmap, norm, xo, yo, origin, **kwargs)
@@ -2288,9 +2288,9 @@ def figaspect(arg):
22882288
# Extract the aspect ratio of the array
22892289
if isarray:
22902290
nr, nc = arg.shape[:2]
2291-
arr_ratio = float(nr) / nc
2291+
arr_ratio = nr / nc
22922292
else:
2293-
arr_ratio = float(arg)
2293+
arr_ratio = arg
22942294

22952295
# Height of user figure defaults
22962296
fig_height = rcParams['figure.figsize'][1]

lib/matplotlib/image.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1453,8 +1453,8 @@ def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
14531453
# need it for the mpl API
14541454
dpi = 100
14551455

1456-
height = float(rows)/dpi*scale
1457-
width = float(cols)/dpi*scale
1456+
height = rows / dpi * scale
1457+
width = cols / dpi * scale
14581458

14591459
extension = extout.lower()
14601460

lib/matplotlib/mlab.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1667,7 +1667,7 @@ def __init__(self, a, standardize=True):
16671667
self.s = s**2
16681668

16691669
# and now the contribution of the individual components
1670-
vars = self.s/float(len(s))
1670+
vars = self.s / len(s)
16711671
self.fracs = vars/vars.sum()
16721672

16731673
def project(self, x, minfrac=0.):
@@ -2172,7 +2172,7 @@ def frange(xini, xfin=None, delta=None, **kw):
21722172
# compute # of points, spacing and return final list
21732173
try:
21742174
npts = kw['npts']
2175-
delta = (xfin-xini)/float(npts-endpoint)
2175+
delta = (xfin-xini) / (npts-endpoint)
21762176
except KeyError:
21772177
npts = int(np.round((xfin-xini)/delta)) + endpoint
21782178
# round finds the nearest, so the endpoint can be up to

lib/matplotlib/patches.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -1085,7 +1085,7 @@ def _recompute_path(self):
10851085
# Partial annulus needs to draw the outer ring
10861086
# followed by a reversed and scaled inner ring
10871087
v1 = arc.vertices
1088-
v2 = arc.vertices[::-1] * float(self.r - self.width) / self.r
1088+
v2 = arc.vertices[::-1] * (self.r - self.width) / self.r
10891089
v = np.vstack([v1, v2, v1[0, :], (0, 0)])
10901090
c = np.hstack([arc.codes, arc.codes, connector, Path.CLOSEPOLY])
10911091
c[len(arc.codes)] = connector
@@ -1179,8 +1179,8 @@ def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
11791179
L = np.hypot(dx, dy)
11801180

11811181
if L != 0:
1182-
cx = float(dx) / L
1183-
sx = float(dy) / L
1182+
cx = dx / L
1183+
sx = dy / L
11841184
else:
11851185
# Account for division by zero
11861186
cx, sx = 0, 1
@@ -1286,12 +1286,12 @@ def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False,
12861286
else:
12871287
raise ValueError("Got unknown shape: %s" % shape)
12881288
if distance != 0:
1289-
cx = float(dx) / distance
1290-
sx = float(dy) / distance
1289+
cx = dx / distance
1290+
sx = dy / distance
12911291
else:
1292-
#Account for division by zero
1292+
# Account for division by zero
12931293
cx, sx = 0, 1
1294-
M = np.array([[cx, sx], [-sx, cx]])
1294+
M = [[cx, sx], [-sx, cx]]
12951295
verts = np.dot(coords, M) + (x + dx, y + dy)
12961296

12971297
Polygon.__init__(self, list(map(tuple, verts)), closed=True, **kwargs)

lib/matplotlib/streamplot.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,8 @@ def __init__(self, grid, mask):
262262
self.grid = grid
263263
self.mask = mask
264264
# Constants for conversion between grid- and mask-coordinates
265-
self.x_grid2mask = float(mask.nx - 1) / grid.nx
266-
self.y_grid2mask = float(mask.ny - 1) / grid.ny
265+
self.x_grid2mask = (mask.nx - 1) / grid.nx
266+
self.y_grid2mask = (mask.ny - 1) / grid.ny
267267

268268
self.x_mask2grid = 1. / self.x_grid2mask
269269
self.y_mask2grid = 1. / self.y_grid2mask

lib/matplotlib/testing/compare.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -367,12 +367,8 @@ def calculate_rms(expectedImage, actualImage):
367367
raise ImageComparisonFailure(
368368
"Image sizes do not match expected size: {0} "
369369
"actual size {1}".format(expectedImage.shape, actualImage.shape))
370-
num_values = expectedImage.size
371-
abs_diff_image = abs(expectedImage - actualImage)
372-
histogram = np.bincount(abs_diff_image.ravel(), minlength=256)
373-
sum_of_squares = np.sum(histogram * np.arange(len(histogram)) ** 2)
374-
rms = np.sqrt(float(sum_of_squares) / num_values)
375-
return rms
370+
# Convert to float to avoid overflowing finite integer types.
371+
return np.sqrt(((expectedImage - actualImage).astype(float) ** 2).mean())
376372

377373

378374
def compare_images(expected, actual, tol, in_decorator=False):

lib/matplotlib/testing/jpl_units/Duration.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def __div__( self, rhs ):
166166
= RETURN VALUE
167167
- Returns the scaled Duration.
168168
"""
169-
return Duration( self._frame, self._seconds / float( rhs ) )
169+
return Duration( self._frame, self._seconds / rhs )
170170

171171
#-----------------------------------------------------------------------
172172
def __rdiv__( self, rhs ):
@@ -178,7 +178,7 @@ def __rdiv__( self, rhs ):
178178
= RETURN VALUE
179179
- Returns the scaled Duration.
180180
"""
181-
return Duration( self._frame, float( rhs ) / self._seconds )
181+
return Duration( self._frame, rhs / self._seconds )
182182

183183
#-----------------------------------------------------------------------
184184
def __str__( self ):

lib/matplotlib/tests/test_collections.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -453,8 +453,8 @@ def test_EllipseCollection():
453453
X, Y = np.meshgrid(x, y)
454454
XY = np.vstack((X.ravel(), Y.ravel())).T
455455

456-
ww = X/float(x[-1])
457-
hh = Y/float(y[-1])
456+
ww = X / x[-1]
457+
hh = Y / y[-1]
458458
aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis
459459

460460
ec = mcollections.EllipseCollection(ww, hh, aa,

lib/matplotlib/tests/test_mlab.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2435,7 +2435,7 @@ def test_contiguous_regions():
24352435
def test_psd_onesided_norm():
24362436
u = np.array([0, 1, 2, 3, 1, 2, 1])
24372437
dt = 1.0
2438-
Su = np.abs(np.fft.fft(u) * dt)**2 / float(dt * u.size)
2438+
Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
24392439
P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none,
24402440
detrend=mlab.detrend_none, noverlap=0, pad_to=None,
24412441
scale_by_freq=None,
@@ -2445,10 +2445,10 @@ def test_psd_onesided_norm():
24452445

24462446

24472447
def test_psd_oversampling():
2448-
"""Test the case len(x) < NFFT for psd(). """
2448+
"""Test the case len(x) < NFFT for psd()."""
24492449
u = np.array([0, 1, 2, 3, 1, 2, 1])
24502450
dt = 1.0
2451-
Su = np.abs(np.fft.fft(u) * dt)**2 / float(dt * u.size)
2451+
Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
24522452
P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none,
24532453
detrend=mlab.detrend_none, noverlap=0, pad_to=None,
24542454
scale_by_freq=None,

lib/matplotlib/textpath.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def get_text_width_height_descent(self, s, prop, ismath):
9999
return w, h, d
100100

101101
fontsize = prop.get_size_in_points()
102-
scale = float(fontsize) / self.FONT_SCALE
102+
scale = fontsize / self.FONT_SCALE
103103

104104
if ismath:
105105
prop = prop.copy()

lib/matplotlib/ticker.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1573,7 +1573,7 @@ def tick_values(self, vmin, vmax):
15731573
"""
15741574
if self.nbins is None:
15751575
return self.locs
1576-
step = max(int(0.99 + len(self.locs) / float(self.nbins)), 1)
1576+
step = max(int(np.ceil(len(self.locs) / self.nbins)), 1)
15771577
ticks = self.locs[::step]
15781578
for i in range(1, step):
15791579
ticks1 = self.locs[i::step]
@@ -2323,7 +2323,7 @@ def get_log_range(lo, hi):
23232323
total_ticks = (a_range[1] - a_range[0]) + (c_range[1] - c_range[0])
23242324
if has_b:
23252325
total_ticks += 1
2326-
stride = max(np.floor(float(total_ticks) / (self.numticks - 1)), 1)
2326+
stride = max(total_ticks // (self.numticks - 1), 1)
23272327

23282328
decades = []
23292329
if has_a:

lib/mpl_toolkits/axes_grid1/axes_size.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def from_any(size, fraction_ref=None):
268268
return Fixed(size)
269269
elif isinstance(size, six.string_types):
270270
if size[-1] == "%":
271-
return Fraction(float(size[:-1])/100., fraction_ref)
271+
return Fraction(float(size[:-1]) / 100, fraction_ref)
272272

273273
raise ValueError("Unknown format")
274274

0 commit comments

Comments
 (0)