我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.trunc()。
def decimal_to_dms(decimal_value): ''' This converts from decimal degrees to DD:MM:SS, returned as a tuple. ''' if decimal_value < 0: negative = True dec_val = fabs(decimal_value) else: negative = False dec_val = decimal_value degrees = trunc(dec_val) minutes_deg = dec_val - degrees minutes_mm = minutes_deg * 60.0 minutes_out = trunc(minutes_mm) seconds = (minutes_mm - minutes_out)*60.0 if negative: degrees = degrees return '-', degrees, minutes_out, seconds else: return '+', degrees, minutes_out, seconds
def jd_to_date(jd): jd = jd + 0.5 F, I = math.modf(jd) I = int(I) A = math.trunc((I - 1867216.25)/36524.25) if I > 2299160: B = I + 1 + A - math.trunc(A / 4.) else: B = I C = B + 1524 D = math.trunc((C - 122.1) / 365.25) E = math.trunc(365.25 * D) G = math.trunc((C - E) / 30.6001) day = C - E + F - math.trunc(30.6001 * G) if G < 13.5: month = G - 1 else: month = G - 13 if month > 2.5: year = D - 4716 else: year = D - 4715 return year, month, day # Find string between 2 strings
def update(self, value): ''' Accepts an input [-1, 1] and applies it as scale between 0 and 4096 ''' assert(value <= 1 and -1 <= value) #convert val to ms pwm_val = 1600 if self.invert: pwm_val -= value * 500 else: pwm_val += value * 500 #SERVO_MIN_ms = 1100 #SERVO_MAX_ms = 2100 stepsPerCycle = 4096 cycleLengthMicroSeconds = 1000000 / self.frequency stepLengthMicroSeconds = cycleLengthMicroSeconds / stepsPerCycle #convert mS to 0-4096 scale pulseLengthInSteps = math.trunc(pwm_val / stepLengthMicroSeconds) - 1 print('Values %d', value, self.channel, pulseLengthInSteps) self.pwm.setPWM(self.channel, 0, pulseLengthInSteps)
def testConversions(self): self.assertTypedEquals(-1, math.trunc(F(-11, 10))) self.assertTypedEquals(-2, math.floor(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-10, 10))) self.assertTypedEquals(-1, int(F(-11, 10))) self.assertTypedEquals(0, round(F(-1, 10))) self.assertTypedEquals(0, round(F(-5, 10))) self.assertTypedEquals(-2, round(F(-15, 10))) self.assertTypedEquals(-1, round(F(-7, 10))) self.assertEqual(False, bool(F(0, 1))) self.assertEqual(True, bool(F(3, 2))) self.assertTypedEquals(0.1, float(F(1, 10))) # Check that __float__ isn't implemented by converting the # numerator and denominator to float before dividing. self.assertRaises(OverflowError, float, int('2'*400+'7')) self.assertAlmostEqual(2.0/3, float(F(int('2'*400+'7'), int('3'*400+'1')))) self.assertTypedEquals(0.1+0j, complex(F(1,10)))
def test_trunc(self): self.assertEqual(math.trunc(1), 1) self.assertEqual(math.trunc(-1), -1) self.assertEqual(type(math.trunc(1)), int) self.assertEqual(type(math.trunc(1.5)), int) self.assertEqual(math.trunc(1.5), 1) self.assertEqual(math.trunc(-1.5), -1) self.assertEqual(math.trunc(1.999999), 1) self.assertEqual(math.trunc(-1.999999), -1) self.assertEqual(math.trunc(-0.999999), -0) self.assertEqual(math.trunc(-100.999), -100) class TestTrunc(object): def __trunc__(self): return 23 class TestNoTrunc(object): pass self.assertEqual(math.trunc(TestTrunc()), 23) self.assertRaises(TypeError, math.trunc) self.assertRaises(TypeError, math.trunc, 1, 2) self.assertRaises(TypeError, math.trunc, TestNoTrunc())
def test_trunc(self): self.assertEqual(math.trunc(1), 1) self.assertEqual(math.trunc(-1), -1) self.assertEqual(type(math.trunc(1)), int) self.assertEqual(type(math.trunc(1.5)), int) self.assertEqual(math.trunc(1.5), 1) self.assertEqual(math.trunc(-1.5), -1) self.assertEqual(math.trunc(1.999999), 1) self.assertEqual(math.trunc(-1.999999), -1) self.assertEqual(math.trunc(-0.999999), -0) self.assertEqual(math.trunc(-100.999), -100) class TestTrunc(object): def __trunc__(self): return 23 class TestNoTrunc(object): pass self.assertEqual(math.trunc(TestTrunc()), 23) self.assertRaises(TypeError, math.trunc) self.assertRaises(TypeError, math.trunc, 1, 2) self.assertRaises((AttributeError, TypeError), math.trunc, TestNoTrunc())
def total_sent(self): # Check that a user_id is set if not bool(self.user_id): raise Exception("HkUser::add_coin(%s): user_id must be set first" % self.username) # Get balance and add sqlcmd = "SELECT SUM(action.coin_val) AS `total` FROM `username` JOIN action ON action.service_id = username.service_id WHERE username.user_id = " + str(int(self.user_id)) + " AND action.from_user= username.username AND action.service_id = username.service_id AND action.state = 'completed' AND action.type='givetip' " # Get balance total = self.haikuberu.get_field(sqlcmd) if total: total = Decimal(total) else: total = 0 return Decimal(Decimal(trunc(total * 100000000)) / 100000000) # Total fiat sent
def total_fiat_sent(self): # Check that a user_id is set if not bool(self.user_id): raise Exception("HkUser::add_coin(%s): user_id must be set first" % self.username) # Get balance and add sqlcmd = "SELECT SUM(action.fiat_val) AS `total` FROM `username` JOIN action ON action.service_id = username.service_id WHERE username.user_id = " + str(int(self.user_id)) + " AND action.from_user= username.username AND action.service_id = username.service_id AND action.state = 'completed' AND action.type='givetip' " # Get balance total = self.haikuberu.get_field(sqlcmd) if total: total = Decimal(total) else: total = 0 return Decimal(Decimal(trunc(total * 100000000)) / 100000000) # Total sent
def total_received(self): # Check that a user_id is set if not bool(self.user_id): raise Exception("HkUser::add_coin(%s): user_id must be set first" % self.username) # Get balance and add sqlcmd = "SELECT SUM(action.coin_val) AS `total` FROM `username` JOIN action ON action.service_id = username.service_id WHERE username.user_id = " + str(int(self.user_id)) + " AND action.to_user= username.username AND action.service_id = username.service_id AND action.state = 'completed' AND action.type='givetip' " # Get balance total = self.haikuberu.get_field(sqlcmd) if total: total = Decimal(total) else: total = 0 return Decimal(Decimal(trunc(total * 100000000)) / 100000000) # Total sent
def total_fiat_received(self): # Check that a user_id is set if not bool(self.user_id): raise Exception("HkUser::add_coin(%s): user_id must be set first" % self.username) # Get balance and add sqlcmd = "SELECT SUM(action.fiat_val) AS `total` FROM `username` JOIN action ON action.service_id = username.service_id WHERE username.user_id = " + str(int(self.user_id)) + " AND action.to_user= username.username AND action.service_id = username.service_id AND action.state = 'completed' AND action.type='givetip' " # Get balance total = self.haikuberu.get_field(sqlcmd) if total: total = Decimal(total) else: total = 0 return Decimal(Decimal(trunc(total * 100000000)) / 100000000) # Add coins
def testConversions(self): self.assertTypedEquals(-1, math.trunc(F(-11, 10))) self.assertTypedEquals(1, math.trunc(F(11, 10))) self.assertTypedEquals(-2, math.floor(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-11, 10))) self.assertTypedEquals(-1, math.ceil(F(-10, 10))) self.assertTypedEquals(-1, int(F(-11, 10))) self.assertTypedEquals(0, round(F(-1, 10))) self.assertTypedEquals(0, round(F(-5, 10))) self.assertTypedEquals(-2, round(F(-15, 10))) self.assertTypedEquals(-1, round(F(-7, 10))) self.assertEqual(False, bool(F(0, 1))) self.assertEqual(True, bool(F(3, 2))) self.assertTypedEquals(0.1, float(F(1, 10))) # Check that __float__ isn't implemented by converting the # numerator and denominator to float before dividing. self.assertRaises(OverflowError, float, int('2'*400+'7')) self.assertAlmostEqual(2.0/3, float(F(int('2'*400+'7'), int('3'*400+'1')))) self.assertTypedEquals(0.1+0j, complex(F(1,10)))
def calQnt(self, price, volume, method, fixedFraction): Equity = self.queryCapital() proportion = 0.15 maxDrawDown = 3800 if method is 'FixedFraction': # TradeRisk = maxDrawDown(data) TradeRisk = maxDrawDown N = fixedFraction * Equity / abs(TradeRisk) if N >= volume * proportion : return math.trunc(volume * proportion) else : return int(np.nan_to_num(N)) # return int(N) if method is 'MaxDrawDown': margin = 0.65 # allocation = maxDrawDown(data) * 1.5 + margin * price allocation = maxDrawDown * 1.5 + margin * price N = Equity / allocation if N >= volume * proportion : return math.trunc(volume * proportion) else : return int(np.nan_to_num(N)) # return int(N) # query capital of self strategy
def divide(self, param, param1): if(isinstance(param,int) or isinstance(param,str)) \ and (isinstance(param1,int) or isinstance(param1,str)): try: if(isinstance(param,str)): param=int(param) if(isinstance(param1,str)): param1=int(param1) except(ValueError): return "???????????????????????????????" try: return math.trunc(param/param1) except(ZeroDivisionError): return "??????" else: return "???????????????????????????????"
def n_lfom_rows(FLOW,HL_LFOM): """This equation states that the open area corresponding to one row can be set equal to two orifices of diameter=row height. If there are more than two orifices per row at the top of the LFOM then there are more orifices than are convenient to drill and more than necessary for good accuracy. Thus this relationship can be used to increase the spacing between the rows and thus increase the diameter of the orifices. This spacing function also sets the lower depth on the high flow rate LFOM with no accurate flows below a depth equal to the first row height. But it might be better to always set then number of rows to 10. The challenge is to figure out a reasonable system of constraints that reliably returns a valid solution. """ N_estimated = (HL_LFOM*np.pi/(2*width_stout(HL_LFOM,HL_LFOM)*FLOW)) #variablerow=min(10,max(4,math.trunc(N_estimated.magnitude))) return 10
def __trunc__(self): return self.clone(math.trunc(self._value))
def __trunc__(self): return self.clone(math.trunc(float(self)))
def decimal_to_hms(decimal_value): ''' This converts from decimal degrees to HH:MM:SS, returned as a tuple. Negative values of degrees are wrapped to 360.0. ''' # wrap to 360.0 if decimal_value < 0: dec_wrapped = 360.0 + decimal_value else: dec_wrapped = decimal_value # convert to decimal hours first dec_hours = dec_wrapped/15.0 if dec_hours < 0: negative = True dec_val = fabs(dec_hours) else: negative = False dec_val = dec_hours hours = trunc(dec_val) minutes_hrs = dec_val - hours minutes_mm = minutes_hrs * 60.0 minutes_out = trunc(minutes_mm) seconds = (minutes_mm - minutes_out)*60.0 if negative: hours = -hours return hours, minutes_out, seconds else: return hours, minutes_out, seconds
def date_to_jd(year,month,day): if month == 1 or month == 2: yearp = year - 1 monthp = month + 12 else: yearp = year monthp = month # this checks where we are in relation to October 15, 1582, the beginning # of the Gregorian calendar. if ((year < 1582) or (year == 1582 and month < 10) or (year == 1582 and month == 10 and day < 15)): # before start of Gregorian calendar B = 0 else: # after start of Gregorian calendar A = math.trunc(yearp / 100.) B = 2 - A + math.trunc(A / 4.) if yearp < 0: C = math.trunc((365.25 * yearp) - 0.75) else: C = math.trunc(365.25 * yearp) D = math.trunc(30.6001 * (monthp + 1)) jd = B + C + D + day + 1720994.5 return jd # Function from: https://gist.github.com/jiffyclub/1294443
def julian_datetime(julianday, milisecond=0): """Return datetime from days since 1/1/4713 BC and ms since midnight. Convert Julian dates according to MetaMorph. >>> julian_datetime(2451576, 54362783) datetime.datetime(2000, 2, 2, 15, 6, 2, 783) """ if julianday <= 1721423: # no datetime before year 1 return None a = julianday + 1 if a > 2299160: alpha = math.trunc((a - 1867216.25) / 36524.25) a += 1 + alpha - alpha // 4 b = a + (1524 if a > 1721423 else 1158) c = math.trunc((b - 122.1) / 365.25) d = math.trunc(365.25 * c) e = math.trunc((b - d) / 30.6001) day = b - d - math.trunc(30.6001 * e) month = e - (1 if e < 13.5 else 13) year = c - (4716 if month > 2.5 else 4715) hour, milisecond = divmod(milisecond, 1000 * 60 * 60) minute, milisecond = divmod(milisecond, 1000 * 60) second, milisecond = divmod(milisecond, 1000) return datetime.datetime(year, month, day, hour, minute, second, milisecond)
def trunc(number: Real) -> int: """ Truncates x to the nearest Integral toward 0. """ return _math.trunc(number) # Operations on collections of numbers
def trunc_example(): # additive series = [] i = 0 for v in range(round(math.pi * 4.5 * 10)): series.append((i, math.trunc(i / 10))) i += 2 print_real(series)
def create_colors(self, hue, num_colors=5, saturation=None, lightness=None): if saturation is None: saturation = 0.9 if lightness is None: lightness = 40 else: lightness *= 100 import math saturation -= math.trunc(saturation) print hue, saturation import colorsys ''' Create n related colours ''' colors = [] for i in xrange(num_colors): ix = i * (1.0/num_colors) _lightness = (lightness + (ix * 40))/100. if _lightness > 1.0: _lightness = 1.0 color = colorsys.hls_to_rgb(hue, _lightness, saturation) hex_color = '#' for part in color: hex_color += '%02x' % int(part * 255) # check and remove any bad values if not re.match('^\#[0-9a-f]{6}$', hex_color): hex_color = '#FFFFFF' colors.append(hex_color) return colors
def testBigFloatComparisons(self): # Because 10**23 can't be represented exactly as a float: self.assertFalse(F(10**23) == float(10**23)) # The first test demonstrates why these are important. self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1))) self.assertTrue(1e23 < F(math.trunc(1e23) + 1)) self.assertFalse(1e23 <= F(math.trunc(1e23) - 1)) self.assertTrue(1e23 > F(math.trunc(1e23) - 1)) self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
def test_trunc(self): for x in range(-250, 250): s = '%0.2f' % (x / 100.0) # should work the same as for floats self.assertEqual(int(Decimal(s)), int(float(s))) # should work the same as to_integral in the ROUND_DOWN mode d = Decimal(s) r = d.to_integral(ROUND_DOWN) self.assertEqual(Decimal(math.trunc(d)), r)
def test_complex(self): self.assertFalse(issubclass(complex, Real)) self.assertTrue(issubclass(complex, Complex)) c1, c2 = complex(3, 2), complex(4,1) # XXX: This is not ideal, but see the comment in math_trunc(). self.assertRaises(TypeError, math.trunc, c1) self.assertRaises(TypeError, operator.mod, c1, c2) self.assertRaises(TypeError, divmod, c1, c2) self.assertRaises(TypeError, operator.floordiv, c1, c2) self.assertRaises(TypeError, float, c1) self.assertRaises(TypeError, int, c1)
def get_balance_string(amount): """Gets the formatted bank balance string for a given amount""" return 'Balance: {0}'.format(math.trunc(amount))
def deposit(self): """ Deposit money to the bank. """ # Don't deposit more money than the user has gross_amount = min( math.trunc(self.__user_balance - self.__bank_traits['min_user_balance']), self._config.bank_deposit) fee = math.trunc(self.calculate_fee(gross_amount)) nett_amount = max(0, gross_amount - fee) # update the bank balance self.update_bank_balance(self.__bank_balance + nett_amount) # subtract from user balance if not self.dry_run: if self._config.bank_type == 'mana': self._hs.set_mp(max(0, self.__user_balance - gross_amount)) elif self._config.bank_type == 'health': self._hs.set_hp(max(0, self.__user_balance - gross_amount)) else: self._hs.set_gp(max(0, self.__user_balance - gross_amount)) message = '{2} Deposit: {0}, Fee: {1}'.format( nett_amount, fee, self.__bank_traits['icon']) self.notify(message)
def withdraw(self): """ Withdraw money from the bank. """ # Don't withdraw more money than the bank has gross_amount = min(self.__bank_balance, self._config.bank_withdraw) # If the traits supports a max user balance, don't withdraw more # than that amount if self.__bank_traits['max_user_balance']: gross_amount = min( max(0, self.__bank_traits['max_user_balance'] - self.__user_balance), gross_amount) print('capping withdrawal to ', gross_amount) fee = math.trunc(self.calculate_fee(gross_amount)) nett_amount = max(0, gross_amount - fee) # update the bank balance new_balance = max(0, self.__bank_balance - gross_amount) self.update_bank_balance(new_balance) # add to user balance if not self.dry_run: if self._config.bank_type == 'mana': self._hs.set_mp(self.__user_balance + nett_amount) elif self._config.bank_type == 'health': self._hs.set_hp(self.__user_balance + nett_amount) else: self._hs.set_gp(self.__user_balance + nett_amount) message = '{2} Withdrew: {0}, Fee: {1}'.format( nett_amount, fee, self.__bank_traits['icon']) self.notify(message)