Python math.trunc() Examples

The following are 30 code examples of math.trunc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 6 votes vote down vote up
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()) 
Example #2
Source Project: BinderFilter   Author: dxwu   File: test_math.py    License: MIT License 6 votes vote down vote up
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()) 
Example #3
Source Project: oss-ftp   Author: aliyun   File: test_math.py    License: MIT License 6 votes vote down vote up
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()) 
Example #4
Source Project: LibrERP   Author: iw3hxn   File: temp_please_no_delete.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def process(self, cr, uid, table, book_datemode=False):
        self.progressIndicator = 0

        notify_progress_step = (self.numberOfLines / 100) + 1

        for self.processed_lines, row_list in enumerate(table, start=1):
            # Import row
            if not self.import_row(cr, uid, row_list, book_datemode):
                self.problems += 1

            if (self.processed_lines % notify_progress_step) == 0:
                cr.commit()
                completed_quota = float(self.processed_lines) / float(self.numberOfLines)
                completed_percentage = math.trunc(completed_quota * 100)
                self.progressIndicator = completed_percentage
                self.updateProgressIndicator(cr, uid, self.bank_statement_import_id)

        self.progressIndicator = 100
        self.updateProgressIndicator(cr, uid, self.bank_statement_import_id)

        return True 
Example #5
Source Project: convertdate   Author: fitnr   File: persian.py    License: MIT License 6 votes vote down vote up
def to_jd(year, month, day):
    '''Determine Julian day from Persian date'''

    if year >= 0:
        y = 474
    else:
        y = 473
    epbase = year - y
    epyear = 474 + (epbase % 2820)

    if month <= 7:
        m = (month - 1) * 31
    else:
        m = (month - 1) * 30 + 6

    return day + m + trunc(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 + trunc(epbase / 2820) * 1029983 + (EPOCH - 1) 
Example #6
Source Project: convertdate   Author: fitnr   File: armenian.py    License: MIT License 6 votes vote down vote up
def from_jd(jd, method=None):
    """Convert a Julian day count to an Armenian date. Use the method of Sarkawag if requested."""
    if method == "sarkawag":
        dc = jd - EPOCH_SARKAWAG
        if dc < 0:
            raise ValueError("Day count out of range for method")
        years = trunc(dc / 365.25)
        yeardays = dc - (365 * years + trunc(years / 4))
        if yeardays == 0:
            yeardays = 366 if years % 4 == 0 else 365
            years -= 1
        months = trunc((yeardays - 1) / 30)
        days = yeardays - (30 * months)
        return years + 533, months + 1, trunc(days)

    dc = jd - EPOCH

    if dc < 0:
        raise ValueError("Day count out of range")

    years = trunc((dc - 1) / 365)
    months = trunc(((dc - 1) % 365) / 30)
    days = dc - (365 * years) - (30 * months)

    return years, months + 1, trunc(days) 
Example #7
Source Project: convertdate   Author: fitnr   File: iso.py    License: MIT License 6 votes vote down vote up
def from_jd(jd):
    '''Return tuple of ISO (year, week, day) for Julian day'''
    year = gregorian.from_jd(jd)[0]
    day = jwday(jd) + 1

    dayofyear = ordinal.from_jd(jd)[1]
    week = trunc((dayofyear - day + 10) / 7)

    # Reset year
    if week < 1:
        week = weeks_per_year(year - 1)
        year = year - 1

    # Check that year actually has 53 weeks
    elif week == 53 and weeks_per_year(year) != 53:
        week = 1
        year = year + 1

    return year, week, day 
Example #8
Source Project: convertdate   Author: fitnr   File: holidays.py    License: MIT License 6 votes vote down vote up
def _easter_julian(year, mode="dionysian"):
    '''Calculate Easter for the orthodox and eastern churches in the Julian calendar.'''
    # Uses Meeus's Julian algorithm.
    meton = (year % 19)
    b = year % 4
    c = year % 7
    d = (19 * meton + 15) % 30
    if mode == "eastern" and meton == 0:
        d = d + 1
    e = (2 * b + 4 * c - d + 6) % 7
    fmj = 113 + d  # Easter full moon (days after -92 March)
    dmj = fmj + e + 1  # Easter Sunday (days after -92 March)
    esmj = trunc(dmj / 31)  # month of Easter Sunday
    esdj = (dmj % 31) + 1  # day of Easter Sunday

    return year, esmj, esdj 
Example #9
Source Project: convertdate   Author: fitnr   File: julian.py    License: MIT License 6 votes vote down vote up
def from_jd(jd):
    '''Calculate Julian calendar date from Julian day'''

    jd += 0.5
    z = trunc(jd)

    a = z
    b = a + 1524
    c = trunc((b - 122.1) / 365.25)
    d = trunc(365.25 * c)
    e = trunc((b - d) / 30.6001)

    if trunc(e < 14):
        month = e - 1
    else:
        month = e - 13

    if trunc(month > 2):
        year = c - 4716
    else:
        year = c - 4715

    day = b - d - trunc(30.6001 * e)

    return (year, month, day) 
Example #10
Source Project: convertdate   Author: fitnr   File: hebrew.py    License: MIT License 6 votes vote down vote up
def from_jd(jd):
    jd = trunc(jd) + 0.5
    count = trunc(((jd - EPOCH) * 98496.0) / 35975351.0)
    year = count - 1
    i = count
    while jd >= to_jd(i, 7, 1):
        i += 1
        year += 1

    if jd < to_jd(year, 1, 1):
        first = 7
    else:
        first = 1

    month = i = first
    while jd > to_jd(year, i, month_days(year, i)):
        i += 1
        month += 1

    day = int(jd - to_jd(year, month, 1)) + 1
    return (year, month, day) 
Example #11
Source Project: convertdate   Author: fitnr   File: bahai.py    License: MIT License 6 votes vote down vote up
def gregorian_nawruz(year):
    '''
        Return Nawruz in the Gregorian calendar.
        Returns a tuple (month, day), where month is always 3
    '''
    if year == 2059:
        return 3, 20

    # Timestamp of spring equinox.
    equinox = Sun.get_equinox_solstice(year, "spring")

    # Get times of sunsets in Tehran near vernal equinox.
    x, y = Angle(TEHRAN[0]), Angle(TEHRAN[1])
    days = trunc(equinox.get_date()[2]), ceil(equinox.get_date()[2])

    for day in days:
        sunset = Epoch(year, 3, day).rise_set(y, x)[1]
        if sunset > equinox:
            return 3, day 
Example #12
Source Project: Fluid-Designer   Author: Microvellum   File: test_fractions.py    License: GNU General Public License v3.0 6 votes vote down vote up
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))) 
Example #13
Source Project: Fluid-Designer   Author: Microvellum   File: test_math.py    License: GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #14
Source Project: SwervinMervin   Author: buntine   File: player.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __level_over_overlay(self, window):
        lo_font      = pygame.font.Font(s.FONTS["fipps"], 38)
        s_font       = pygame.font.Font(s.FONTS["retro_computer"], 30)
        txt_lo       = lo_font.render("Level Complete!", 1, s.COLOURS["dark_text"])
        txt_lap      = s_font.render("Best Lap", 1, s.COLOURS["dark_text"])
        txt_lap_v    = s_font.render("%.1fs" % round(self.fastest_lap, 1), 1, s.COLOURS["dark_text"])
        txt_bonus    = s_font.render("Time bonus", 1, s.COLOURS["dark_text"])
        txt_bonus_v  = s_font.render(str(math.trunc(self.time_bonus)), 1, s.COLOURS["dark_text"])
        txt_points   = s_font.render("Points", 1, s.COLOURS["dark_text"])
        txt_points_v = s_font.render(str(math.trunc(self.points)), 1, s.COLOURS["dark_text"])
        overlay      = pygame.Surface(s.DIMENSIONS, pygame.SRCALPHA)

        overlay.fill((255, 255, 255, 150))
        overlay.blit(txt_lo, (s.DIMENSIONS[0] / 2 - txt_lo.get_size()[0] / 2, 20))
        overlay.blit(txt_lap, (20, 180))
        overlay.blit(txt_lap_v, (s.DIMENSIONS[0] - txt_lap_v.get_size()[0] - 10, 190))
        overlay.blit(txt_bonus, (20, 260))
        overlay.blit(txt_bonus_v, (s.DIMENSIONS[0] - txt_bonus_v.get_size()[0] - 10, 270))
        overlay.blit(txt_points, (20, 340))
        overlay.blit(txt_points_v, (s.DIMENSIONS[0] - txt_points_v.get_size()[0] - 10, 350))

        window.blit(overlay, (0,0)) 
Example #15
Source Project: ironpython3   Author: IronLanguages   File: test_fractions.py    License: Apache License 2.0 6 votes vote down vote up
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))) 
Example #16
Source Project: aws-ops-automator   Author: awslabs   File: build_task_custom_resource.py    License: Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, set):
            return list(o)
        if isinstance(o, datetime):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return str(trunc(o))
        if isinstance(o, Exception):
            return str(o)
        return json.JSONEncoder.default(self, o) 
Example #17
Source Project: aws-ops-automator   Author: awslabs   File: task_tracking_table.py    License: Apache License 2.0 5 votes vote down vote up
def update_task(self, action_id, task=None, task_metrics=None, status=None, status_data=None):
        """
        Updates the status of an action in the tracking table
        :param action_id: action id
        :param task: name of the task
        :param task_metrics: collect task metrics
        :param status: new action status
        :param status_data: additional date as a dictionary to be added to the tracking table
        :return:
        """

        data = {handlers.TASK_TR_UPDATED: datetime.now().isoformat(), handlers.TASK_TR_UPDATED_TS: int(time())}
        if status is not None:
            data[handlers.TASK_TR_STATUS] = status

        # for completed tasks remove the concurrency id and the wait for completion start time so these items
        # are not longer visible the GSI of these tables
        if status in NOT_LONGER_ACTIVE_STATUSES:
            data[handlers.TASK_TR_CONCURRENCY_ID] = None
            data[handlers.TASK_TR_LAST_WAIT_COMPLETION] = None

            # set TTL for tasks to be remove after retention period
            if os.getenv(handlers.ENV_TASK_CLEANUP_ENABLED, "").lower() == "true":
                if status == handlers.STATUS_COMPLETED or os.getenv(handlers.ENV_KEEP_FAILED_TASKS, "").lower() == "false":
                    task_retention_hours = int(os.getenv(handlers.ENV_TASK_RETENTION_HOURS, 168))
                    ttl = (task_retention_hours * 3600) + math.trunc(time())
                    data[handlers.TASK_TR_TTL] = ttl

        if status_data is not None:
            for i in status_data:
                data[i] = status_data[i]

            data = as_dynamo_safe_types(data)
        self._update(action_id, data)

        if task is not None:
            self._put_task_status_metrics(task, status, task_level=task_metrics, data=status_data) 
Example #18
Source Project: segpy   Author: sixty-north   File: ibm_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __ceil__(self):
        t = trunc(self)
        return t if self.signbit else t + 1 
Example #19
Source Project: segpy   Author: sixty-north   File: ibm_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __floor__(self):
        t = trunc(self)
        return t - 1 if self.signbit else t 
Example #20
Source Project: segpy   Author: sixty-north   File: ibm_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __int__(self):
        return trunc(self) 
Example #21
Source Project: segpy   Author: sixty-north   File: test_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_trunc_above_zero(self, i, f):
        assume(f != 1.0)
        ieee = i + f
        ibm = IBMFloat.from_float(ieee)
        assert trunc(ibm) == i 
Example #22
Source Project: segpy   Author: sixty-north   File: test_float.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_trunc_below_zero(self, i, f):
        assume(f != 1.0)
        ieee = i - f
        ibm = IBMFloat.from_float(ieee)
        assert trunc(ibm) == i 
Example #23
Source Project: ironpython2   Author: IronLanguages   File: test_fractions.py    License: Apache License 2.0 5 votes vote down vote up
def testConversions(self):
        self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
        self.assertTypedEquals(-1, int(F(-11, 10)))
        self.assertTypedEquals(1, math.trunc(F(11, 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, long('2'*400+'7'))
        self.assertAlmostEqual(2.0/3,
                                float(F(long('2'*400+'7'), long('3'*400+'1'))))

        self.assertTypedEquals(0.1+0j, complex(F(1,10))) 
Example #24
Source Project: ironpython2   Author: IronLanguages   File: test_fractions.py    License: Apache License 2.0 5 votes vote down vote up
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)) 
Example #25
Source Project: ironpython2   Author: IronLanguages   File: test_decimal.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example #26
Source Project: ironpython2   Author: IronLanguages   File: test_abstract_numbers.py    License: Apache License 2.0 5 votes vote down vote up
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(AttributeError, math.trunc, c1)
        self.assertRaises(TypeError, float, c1)
        self.assertRaises(TypeError, int, c1) 
Example #27
Source Project: ironpython2   Author: IronLanguages   File: python26.py    License: Apache License 2.0 5 votes vote down vote up
def test_trunc():
    import sys, math
    
    test_values = [-1, 0, 1, -1L, 0L, 1L, -1.0, 0.0, 1.0, sys.maxint + 0.5,
                   -sys.maxint - 0.5, 9876543210, -9876543210, -1e100, 1e100]
    
    for value in test_values:
        AreEqual(long(value), math.trunc(value))
        if type(value) == float:
            AreEqual(type(math.trunc(value)) == int, -sys.maxint - 1 <= value <= sys.maxint)
        else:
            AreEqual(type(value), type(math.trunc(value)))

# A small extension of CPython's test_struct.py, which does not make sure that empty
# dictionaries are interpreted as false 
Example #28
Source Project: bene   Author: zappala   File: tcp-plot.py    License: GNU General Public License v2.0 5 votes vote down vote up
def add_to_bucket(self,time,size):
        bucket = math.trunc(time*10.0)/10.0
        if bucket not in self.buckets:
            self.buckets[bucket] = 0
        self.buckets[bucket] += size*8/(1000000*0.1) 
Example #29
Source Project: daf-recipes   Author: italia   File: cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source Project: BinderFilter   Author: dxwu   File: test_fractions.py    License: MIT License 5 votes vote down vote up
def testConversions(self):
        self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
        self.assertTypedEquals(-1, int(F(-11, 10)))
        self.assertTypedEquals(1, math.trunc(F(11, 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, long('2'*400+'7'))
        self.assertAlmostEqual(2.0/3,
                                float(F(long('2'*400+'7'), long('3'*400+'1'))))

        self.assertTypedEquals(0.1+0j, complex(F(1,10)))