我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.fmod()。
def advance_wrap(self, steps): assert self.is_valid() if steps == 0: return self step_shift = 2 * (self.__class__.MAX_LEVEL - self.level()) + 1 if steps < 0: min_steps = -(self.id() >> step_shift) if steps < min_steps: step_wrap = self.__class__.WRAP_OFFSET >> step_shift # cannot use steps %= step_wrap as Python % different to C++ steps = int(math.fmod(steps, step_wrap)) if steps < min_steps: steps += step_wrap else: max_steps = (self.__class__.WRAP_OFFSET - self.id()) >> step_shift if steps > max_steps: step_wrap = self.__class__.WRAP_OFFSET >> step_shift # cannot use steps %= step_wrap as Python % different to C++ steps = int(math.fmod(steps, step_wrap)) if steps > max_steps: steps -= step_wrap return self.__class__(self.id() + (steps << step_shift))
def point_inside_loop(loop_coords, mous_loc): nverts = len(loop_coords) # vectorize our two item tuple out = Vector(outside_loop(loop_coords)) vec_mous = Vector(mous_loc) intersections = 0 for i in range(0, nverts): a = Vector(loop_coords[i-1]) b = Vector(loop_coords[i]) if intersect_line_line_2d(vec_mous, out, a, b): intersections += 1 inside = False if fmod(intersections, 2): inside = True return inside # === OpenGL drawing functions ===
def get_position(self, delta): """Update the spinner position after the specified delta (in seconds) has elapsed. Will return the new spinner position, a continuous value from 0...<10. """ # Increment elapsed time and compute the current velocity after a # decay of the initial velocity. self._elapsed += delta current_velocity = self._velocity*math.pow(self._decay, self._elapsed) # Update position based on the current_velocity and elapsed time. self._position += current_velocity*delta # Make sure the position stays within values that range from 0 to <10. self._position = math.fmod(self._position, 10.0) if self._position < 0.0: self._position += 10.0 return self._position # Define animation classes. Each animation needs to have an update function # which takes in the current spinner position and a selected primary and # secondary color (3-tuple of RGB bytes) and will render a frame of spinner # animation.
def testFmod(self): self.assertRaises(TypeError, math.fmod) self.ftest('fmod(10,1)', math.fmod(10,1), 0) self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0) self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1) self.ftest('fmod(-10,1)', math.fmod(-10,1), 0) self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0) self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1) self.assertTrue(math.isnan(math.fmod(NAN, 1.))) self.assertTrue(math.isnan(math.fmod(1., NAN))) self.assertTrue(math.isnan(math.fmod(NAN, NAN))) self.assertRaises(ValueError, math.fmod, 1., 0.) self.assertRaises(ValueError, math.fmod, INF, 1.) self.assertRaises(ValueError, math.fmod, NINF, 1.) self.assertRaises(ValueError, math.fmod, INF, 0.) self.assertEqual(math.fmod(3.0, INF), 3.0) self.assertEqual(math.fmod(-3.0, INF), -3.0) self.assertEqual(math.fmod(3.0, NINF), 3.0) self.assertEqual(math.fmod(-3.0, NINF), -3.0) self.assertEqual(math.fmod(0.0, 3.0), 0.0) self.assertEqual(math.fmod(0.0, NINF), 0.0)
def wrap360(euler_angle): """ Wrap angle to 360 Args: euler_angle (float): Euler angle Returns: Wrapped angle """ if euler_angle > 0.0: return fmod(euler_angle, 360.0) else: euler_angle += 360.0 return fmod(euler_angle, 360.0)
def testFmod(self): self.assertRaises(TypeError, math.fmod) self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0) self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0) self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0) self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0) self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0) self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0) self.assertTrue(math.isnan(math.fmod(NAN, 1.))) self.assertTrue(math.isnan(math.fmod(1., NAN))) self.assertTrue(math.isnan(math.fmod(NAN, NAN))) self.assertRaises(ValueError, math.fmod, 1., 0.) self.assertRaises(ValueError, math.fmod, INF, 1.) self.assertRaises(ValueError, math.fmod, NINF, 1.) self.assertRaises(ValueError, math.fmod, INF, 0.) self.assertEqual(math.fmod(3.0, INF), 3.0) self.assertEqual(math.fmod(-3.0, INF), -3.0) self.assertEqual(math.fmod(3.0, NINF), 3.0) self.assertEqual(math.fmod(-3.0, NINF), -3.0) self.assertEqual(math.fmod(0.0, 3.0), 0.0) self.assertEqual(math.fmod(0.0, NINF), 0.0)
def next_overpass (date1, path, sat): """ provides the next overpass for path after date1 """ date0_L5 = datetime.datetime(1985,5,4) date0_L7 = datetime.datetime(1999,1,11) date0_L8 = datetime.datetime(2013,5,1) if sat == 'LT5': date0 = date0_L5 elif sat == 'LE7': date0 = date0_L7 elif sat == 'LC8': date0 = date0_L8 next_day=math.fmod((date1-date0).days-cycle_day(path)+1,16) if next_day != 0: date_overpass = date1+datetime.timedelta(16-next_day) else: date_overpass = date1 return date_overpass
def drem(x, y): """Like fmod but rounds to nearest integer instead of floor.""" xd = decimal.Decimal(x) yd = decimal.Decimal(y) return float(xd.remainder_near(yd))
def AngNormalize(x): """reduce angle to (-180,180]""" y = math.fmod(x, 360) # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360) = +0.0 # This fixes this bug. See also Math::AngNormalize in the C++ library. # sincosd has a similar fix. y = x if x == 0 else y return (y + 360 if y <= -180 else (y if y <= 180 else y - 360))
def sincosd(x): """Compute sine and cosine of x in degrees.""" r = math.fmod(x, 360) q = Math.nan if Math.isnan(r) else int(math.floor(r / 90 + 0.5)) r -= 90 * q; r = math.radians(r) s = math.sin(r); c = math.cos(r) q = q % 4 if q == 1: s, c = c, -s elif q == 2: s, c = -s, -c elif q == 3: s, c = -c, s # Remove the minus sign on -0.0 except for sin(-0.0). # On Windows 32-bit with python 2.7, math.fmod(-0.0, 360) = +0.0 # (x, c) here fixes this bug. See also Math::sincosd in the C++ library. # AngNormalize has a similar fix. s, c = (x, c) if x == 0 else (0.0+s, 0.0+c) return s, c
def _transitdirect(lon1, lon2): """Count crossings of prime meridian for AddEdge.""" # We want to compute exactly # int(floor(lon2 / 360)) - int(floor(lon1 / 360)) # Since we only need the parity of the result we can use std::remquo but # this is buggy with g++ 4.8.3 and requires C++11. So instead we do lon1 = math.fmod(lon1, 720.0); lon2 = math.fmod(lon2, 720.0) return ( (0 if ((lon2 >= 0 and lon2 < 360) or lon2 < -360) else 1) - (0 if ((lon1 >= 0 and lon1 < 360) or lon1 < -360) else 1) )
def normalizeLongitude(num): '''Normalize the Longitude between -180 and 180 degrees''' num += 180.0 num = math.fmod(num, 360.0) if num < 0: num += 180 else: num -= 180 return num
def test_frac(self): self._testMath(torch.frac, lambda x: math.fmod(x, 1))
def test_trunc(self): self._testMath(torch.trunc, lambda x: x - math.fmod(x, 1))
def test_fmod(self): m1 = torch.Tensor(10,10).uniform_(-10., 10.) res1 = m1.clone() q = 2.1 res1[:,3].fmod_(q) res2 = m1.clone() for i in range(m1.size(1)): res2[i,3] = math.fmod(res2[i,3], q) self.assertEqual(res1, res2)
def test_cfmod(self): self._test_cop(torch.fmod, math.fmod)
def _func(self, x): return 75 if (math.fmod(x, 50) <= 25) else 25
def __dxftags__(self): def curve_point(alpha): alpha = radians(alpha) point = (cos(alpha) * self.rx, sin(alpha) * self.ry) point = rotate_2d(point, radians(self.rotation)) x, y = vadd(self.center, point) return (x, y, zaxis) def normalize_angle(angle): angle = fmod(angle, 360.) if angle < 0: angle += 360. return angle zaxis = 0. if len(self.center)<3 else self.center[2] points = [] delta = (self.endangle - self.startangle) / self.segments for segment in xrange(self.segments): alpha = self.startangle + delta * segment points.append(curve_point(alpha)) polyline = Polyline(points, color=self.color, layer=self.layer, linetype=self.linetype) if equals_almost(self.startangle, normalize_angle(self.endangle)): polyline.close() return polyline.__dxftags__()
def normalize_angle(angle): """ return an angle between 0 and 2*pi """ angle = math.fmod(angle, DOUBLE_PI) if angle < 0: angle += DOUBLE_PI return angle
def next_time(t): next_t = list(t) if math.fmod(next_t[3], 2) == 0: next_t[3] += 2 else: next_t[3] += 1 next_t = next_t[:4] + [0 for i in range(5)] return next_t
def get_position(self, delta): # Increment elapsed time and compute the current velocity after a # decay of the initial velocity. self._elapsed += delta current_velocity = self._velocity*math.pow(self._decay, self._elapsed) self._position += current_velocity*delta # Make sure the position stays within values that range from 0 to <10. self._position = math.fmod(self._position, 10.0) if self._position < 0.0: self._position += 10.0 return self._position # Initialize NeoPixels and accelerometer.
def _mgrsString(zone, letters, easting, northing, precision): """ Constructs an MGRS string from its component parts @param zone - UTM zone @param letters - MGRS coordinate string letters @param easting - easting value @param northing - northing value @param precision - precision level of MGRS string @returns - MGRS coordinate string """ mrgs = '' if zone: tmp = str(zone) mgrs = tmp.zfill(3 - len(tmp)) else: mgrs = ' ' for i in range(3): mgrs += list(ALPHABET.keys())[list(ALPHABET.values()).index(letters[i])] easting = math.fmod(easting + 1e-8, 100000.0) if easting >= 99999.5: easting = 99999.0 mgrs += str(int(easting)).rjust(5, '0')[:precision] northing = math.fmod(northing + 1e-8, 100000.0) if northing >= 99999.5: northing = 99999.0 mgrs += str(int(northing)).rjust(5, '0')[:precision] return mgrs
def test_fmod(self): m1 = torch.Tensor(10, 10).uniform_(-10., 10.) res1 = m1.clone() q = 2.1 res1[:, 3].fmod_(q) res2 = m1.clone() for i in range(m1.size(1)): res2[i, 3] = math.fmod(res2[i, 3], q) self.assertEqual(res1, res2)
def feature_inview_2d(f, x, theta, rmax, thmax): """Checks to see wheter features is in view of robot Parameters ---------- f : np.array of size 2 Feature position x : np.array of size 2 Robot position theta : float Robot's current heading in radians rmax : float Max sensor range thmax : float Max sensor bearing Returns ------- Boolean to denote whether feature is in view of robot """ # Distance in x and y dx = f[0] - x[0] dy = f[1] - x[1] # Calculate range and bearing r = sqrt(dx**2 + dy**2) th = fmod(atan2(dy, dx) - theta, 2 * pi) if th > pi: th = th - 2 * pi # Check to see if range and bearing is within view if ((r < rmax) and (abs(th) < thmax)): return True else: return False
def wrap180(euler_angle): """ Wrap angle to 180 Args: euler_angle (float): Euler angle Returns: Wrapped angle """ return fmod((euler_angle + 180.0), 360.0) - 180.0
def gmst(lod, jul_day): '''Computes smoothed Greenwich siderial time: http://articles.adsabs.harvard.edu//full/1982A%26A...105..359A/0000360.000.html''' tut1 = (jul_day - 2451545.0) / 36525.0 seconds = -6.2e-6 * tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + \ (876600.0 * 3600.0 + 8640184.812866) * tut1 + 67310.54841 _theta = 2 * pi * fmod(seconds / 86400.0, 1.0) theta = _theta if _theta > 0 else _theta + 2*pi omega = 7.29211514670698e-5 * (1.0 - lod / 86400.0) return theta, omega
def wrapTo2PI(stradiance): result = 0.0 if stradiance == pi2: return pi2; else: result = math.fmod(stradiance, pi2); if result < 0: return (result + pi2); return result
def divfmod(x, y): fmod = math.fmod(x, y) div = (x-fmod)//y return div, fmod
def normalize_angle_positive(angle): """ map an angle from 0 to 2pi """ return fmod(fmod(angle, 2.0*pi) + 2.0*pi, 2.0*pi) # map to -pi to +pi
def addHandles(self): self.removeHandles() self.cp_cidmap = {} print(len(self.cc.road)) for r in self.cc.road: print(len(r)) cids = self.addMoveHandle(r) for cid in cids: self.r_cidmap[cid] = r self.imap[r] = cids self.canvas.tag_lower("rail","segment") sys.stdout.flush() minslotlen = 50 #tex = m.fmod(self.cc.length(),minslotlen) #numslots = int((self.cc.length() - tex)/minslotlen + 2) numslots = int(self.cc.length()/minslotlen + 2) ex = (self.cc.length() - numslots*minslotlen)/numslots slotlen = minslotlen + ex try: self.canvas.delete("slots") except tk.TclError: pass for i in range(numslots): s = i*slotlen op, ot = self.cc.pointAndTangentAt(s) on = la.perp2ccw(ot) p1 = op + 30*la.unit(on) p2 = op - 30*la.unit(on) self.canvas.create_polygon([(p1[0],p1[1]),(p2[0],p2[1])],outline="black",tags="slots")
def drawContours(self, path): # print("load contours",path) try: self.canvas.delete("contour") except tk.TclError: pass import re self.contours = np.load(path) ex = self.scene["ex"] lf = len(self.contours.files) for a in self.contours.files: cs = self.contours[a] h = int(re.findall('\d+', a)[0]) h /= lf # print("file",a,h) # print("contours",len(cs)) col = colorsys.rgb_to_hsv(0.7, 0.9, 0.85) hue = col[0] - h / 2 hue = m.fmod(hue, 1) col = (hue, max(0, min(col[1], 1)), max(0, min(col[2], 1))) col = colorsys.hsv_to_rgb(*col) hexcol = rgb2hex(col) for c in cs: if len(c): cc = [((x[1] - 512) / 1024 * ex * 2, (x[0] - 512) / 1024 * ex * 2) for x in c] if la.norm(c[-1] - c[0]) < 0.01: self.canvas.create_polygon(cc, fill="", outline=hexcol, width=7, tag="contour") else: self.canvas.create_line(cc, fill=hexcol, width=7, tag="contour") try: self.canvas.tag_lower("contour") except tk.TclError: pass sys.stdout.flush()
def halton2(dim, nsims): """ la fonction ne crash plus. Version 2 de la suite d'halton sans la librairie Python existante. """ h = np.empty(nsims * dim) h.fill(np.nan) p = np.empty(nsims) p.fill(np.nan) Base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] lognsims = log(nsims + 1) for i in range(dim): base = Base[i] n = int(ceil(lognsims / log(base))) for t in range(n): p[t] = pow(base, -(t + 1) ) for j in range(nsims): d = j + 1 somme = fmod(d, base) * p[0] for t in range(1, n): d = floor(d / base) somme += fmod(d, base) * p[t] h[j*dim + i] = somme return norm.ppf(h.reshape(dim, nsims))
def SanitizeAngleValue(kernelCenter, angle): numDistinctLines = kernelCenter * 4 angle = math.fmod(angle, 180.0) validLineAngles = np.linspace(0,180, numDistinctLines, endpoint = False) angle = nearestValue(angle, validLineAngles) return angle
def cycle_day (path): """ provides the day in cycle given the path number """ cycle_day_path1 = 5 cycle_day_increment = 7 nb_days_after_day1 = cycle_day_path1 + cycle_day_increment*(path-1) cycle_day_path = math.fmod(nb_days_after_day1,16) if path >= 98: #change date line cycle_day_path += 1 return cycle_day_path