Python math.modf() Examples

The following are 30 code examples for showing how to use math.modf(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: aerospike-admin   Author: aerospike   File: sys_section_parser.py    License: Apache License 2.0 6 votes vote down vote up
def _get_bytes_from_float(memstr, shift, mem_unit_len):
    try:
        if mem_unit_len == 0:
            memnum = float(memstr)
        else:
            memnum = float(memstr[:-mem_unit_len])
    except ValueError:
        return memstr

    if memstr == '0':
        return int(0)
    f, i = math.modf(memnum)
    num = 1 << shift
    totalmem = (i * num) + (f * num)
    return int(totalmem)

# Used in top command output 
Example 2
Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, (v1,v2), (e1,e2)))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 3
Project: market_predictor_cnn   Author: rrguardo   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _encode_val(value):
        """
            Encode a tick value(open or high or low, etc) as 2 RBG pixels.
            One pixel for interger section and other pixel for fractional section.
        """
        fract, inte = math.modf(value)
        fract = str(int(fract*1000000))
        inte = str(int(inte))
        for i in range(0, 6-len(inte)):
            inte = "0" + inte
        for i in range(0, 6-len(fract)):
            fract = "0" + fract
        pix1 = (int(inte[:2]) + 100,
                int(inte[2:4]) + 100,
                int(inte[4:]) + 100)
        pix2 = (int(fract[:2]) + 100,
                int(fract[2:4]) + 100,
                int(fract[4:]) + 100)
        return [pix1, pix2] 
Example 4
Project: BinderFilter   Author: dxwu   File: test_math.py    License: MIT License 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, (v1,v2), (e1,e2)))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 5
Project: oss-ftp   Author: aliyun   File: test_math.py    License: MIT License 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, (v1,v2), (e1,e2)))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 6
Project: winapi-deobfuscation   Author: cylance   File: cut.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _get_use_and_withhold_idxs_for_filepath(self, N_samples_in_filepath, 
			start_idx_for_filepath,  train_pct_for_filepath, seed):
		"""
		
		Given characteristics for a filepath (# samples, training pct, and starting idx relative to the corpus),
		uses random selection to return train and test (corpus-based) indices.

		Arguments:
			N_samples_in_filepath: Int 
			start_idx_for_filepath: Int 
			train_pct_for_filepath: Float. 
			seed: Int
				Sets random seed. 
		"""
		np.random.seed(seed=seed)
		permuted_row_idxs=np.random.permutation(N_samples_in_filepath)
		samples_to_use_in_filepath_as_float=train_pct_for_filepath*N_samples_in_filepath
		decimal_part, int_part = math.modf(samples_to_use_in_filepath_as_float)
		last_train_idx_in_this_file=int(int_part)+np.random.binomial(n=1, p=decimal_part) #important if only one sample per file 
		train_indices = permuted_row_idxs[:last_train_idx_in_this_file]+start_idx_for_filepath		
		test_indices = permuted_row_idxs[last_train_idx_in_this_file:]+start_idx_for_filepath		
		return train_indices, test_indices 
Example 7
Project: Build-CNN-or-LSTM-or-CNNLSTM-with-speech-features   Author: a-n-rose   File: prep_noise.py    License: MIT License 6 votes vote down vote up
def match_length(noise,sr,desired_length):
    noise2 = np.array([])
    final_noiselength = sr*desired_length
    original_noiselength = len(noise)
    frac, int_len = math.modf(final_noiselength/original_noiselength)
    for i in range(int(int_len)):
        noise2 = np.append(noise2,noise)
    if frac:
        max_index = int(original_noiselength*frac)
        end_index = len(noise) - max_index
        rand_start = random.randrange(0,end_index)
        noise2 = np.append(noise2,noise[rand_start:rand_start+max_index])
    if len(noise2) != final_noiselength:
        diff = int(final_noiselength - len(noise2))
        if diff < 0:
            noise2 = noise2[:diff]
        else:
            noise2 = np.append(noise2,np.zeros(diff,))
    return(noise2) 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: datetime.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _fromtimestamp(cls, t, utc, tz):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """
        frac, t = _math.modf(t)
        us = round(frac * 1e6)
        if us >= 1000000:
            t += 1
            us -= 1000000
        elif us < 0:
            t -= 1
            us += 1000000

        converter = _time.gmtime if utc else _time.localtime
        y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us, tz) 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_math.py    License: GNU General Public License v3.0 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 10
def dd2dms(lat, lon):
        latf, latn = math.modf(lat)
        lonf, lonn = math.modf(lon)
        latd = int(latn)
        latm = int(latf * 60)
        lats = (lat - latd - latm / 60) * 3600.00
        lond = int(lonn)
        lonm = int(lonf * 60)
        lons = (lon - lond - lonm / 60) * 3600.00
        compass = {
            'lat': ('N','S'),
            'lon': ('E','W')
        }
        lat_compass = compass['lat'][0 if latd >= 0 else 1]
        lon_compass = compass['lon'][0 if lond >= 0 else 1]
        return '{}º {}\' {:.2f}" {}, {}º {}\' {:.2f}" {}'.format(abs(latd), 
        	abs(latm), abs(lats), lat_compass, abs(lond), 
        	abs(lonm), abs(lons), lon_compass) 
Example 11
Project: ironpython3   Author: IronLanguages   File: datetime.py    License: Apache License 2.0 6 votes vote down vote up
def _fromtimestamp(cls, t, utc, tz):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """
        frac, t = _math.modf(t)
        us = round(frac * 1e6)
        if us >= 1000000:
            t += 1
            us -= 1000000
        elif us < 0:
            t -= 1
            us += 1000000

        converter = _time.gmtime if utc else _time.localtime
        y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us, tz) 
Example 12
Project: ironpython3   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 13
Project: gcblue   Author: gcblue   File: test_math.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, (v1,v2), (e1,e2)))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 14
Project: ezdxf   Author: mozman   File: vector.py    License: MIT License 6 votes vote down vote up
def angle_between(self, other: Any) -> float:
        """
        Returns angle between `self` and `other` in radians. +angle is counter clockwise orientation.

        Args:
            other: :class:`Vector` compatible object

        """
        v2 = self.__class__(other)
        cos_theta = self.dot(v2) / (self.magnitude * v2.magnitude)
        abs_cos_theta = math.fabs(cos_theta)
        if abs_cos_theta > 1.0:
            if abs_cos_theta - 1.0 < 1e-5:
                cos_theta = math.modf(cos_theta)[1]
            else:
                raise ValueError(f'domain error: {cos_theta}')
        return math.acos(cos_theta) 
Example 15
Project: BMN-Boundary-Matching-Network   Author: JJBOY   File: models.py    License: MIT License 6 votes vote down vote up
def _get_interp1d_bin_mask(self, seg_xmin, seg_xmax, tscale, num_sample, num_sample_perbin):
        # generate sample mask for a boundary-matching pair
        plen = float(seg_xmax - seg_xmin)
        plen_sample = plen / (num_sample * num_sample_perbin - 1.0)
        total_samples = [
            seg_xmin + plen_sample * ii
            for ii in range(num_sample * num_sample_perbin)
        ]
        p_mask = []
        for idx in range(num_sample):
            bin_samples = total_samples[idx * num_sample_perbin:(idx + 1) * num_sample_perbin]
            bin_vector = np.zeros([tscale])
            for sample in bin_samples:
                sample_upper = math.ceil(sample)
                sample_decimal, sample_down = math.modf(sample)
                if int(sample_down) <= (tscale - 1) and int(sample_down) >= 0:
                    bin_vector[int(sample_down)] += 1 - sample_decimal
                if int(sample_upper) <= (tscale - 1) and int(sample_upper) >= 0:
                    bin_vector[int(sample_upper)] += sample_decimal
            bin_vector = 1.0 / num_sample_perbin * bin_vector
            p_mask.append(bin_vector)
        p_mask = np.stack(p_mask, axis=1)
        return p_mask 
Example 16
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: datetime.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _fromtimestamp(cls, t, utc, tz):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """
        frac, t = _math.modf(t)
        us = round(frac * 1e6)
        if us >= 1000000:
            t += 1
            us -= 1000000
        elif us < 0:
            t -= 1
            us += 1000000

        converter = _time.gmtime if utc else _time.localtime
        y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us, tz) 
Example 17
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_math.py    License: GNU General Public License v3.0 6 votes vote down vote up
def testModf(self):
        self.assertRaises(TypeError, math.modf)

        def testmodf(name, result, expected):
            (v1, v2), (e1, e2) = result, expected
            if abs(v1-e1) > eps or abs(v2-e2):
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
        testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

        self.assertEqual(math.modf(INF), (0.0, INF))
        self.assertEqual(math.modf(NINF), (-0.0, NINF))

        modf_nan = math.modf(NAN)
        self.assertTrue(math.isnan(modf_nan[0]))
        self.assertTrue(math.isnan(modf_nan[1])) 
Example 18
Project: hapi   Author: PaddlePaddle   File: modeling.py    License: Apache License 2.0 6 votes vote down vote up
def _get_interp1d_bin_mask(seg_xmin, seg_xmax, tscale, num_sample,
                           num_sample_perbin):
    """ generate sample mask for a boundary-matching pair """
    plen = float(seg_xmax - seg_xmin)
    plen_sample = plen / (num_sample * num_sample_perbin - 1.0)
    total_samples = [
        seg_xmin + plen_sample * ii
        for ii in range(num_sample * num_sample_perbin)
    ]
    p_mask = []
    for idx in range(num_sample):
        bin_samples = total_samples[idx * num_sample_perbin:(idx + 1) *
                                    num_sample_perbin]
        bin_vector = np.zeros([tscale])
        for sample in bin_samples:
            sample_upper = math.ceil(sample)
            sample_decimal, sample_down = math.modf(sample)
            if int(sample_down) <= (tscale - 1) and int(sample_down) >= 0:
                bin_vector[int(sample_down)] += 1 - sample_decimal
            if int(sample_upper) <= (tscale - 1) and int(sample_upper) >= 0:
                bin_vector[int(sample_upper)] += sample_decimal
        bin_vector = 1.0 / num_sample_perbin * bin_vector
        p_mask.append(bin_vector)
    p_mask = np.stack(p_mask, axis=1)
    return p_mask 
Example 19
Project: bard   Author: antlarr   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def formatLength(seconds):
    hours, remainder = divmod(seconds, 3600)
    minutes, remseconds = divmod(remainder, 60)
    string = ''
    if hours:
        minformat = '%02d'
    else:
        minformat = '%d'

    if hours or minutes:
        minseconds = '%02d'
    else:
        minseconds = '%d'

    string = ':'.join([y % x for x, y in [(hours, '%d'), (minutes, minformat),
                                          (remseconds, minseconds)] if x])
    miliseconds = math.modf(remseconds)[0]
    if miliseconds:
        string += '{0:.3f}'.format(miliseconds)[1:]
    return string 
Example 20
Project: kivy-smoothie-host   Author: wolfmanjm   File: hb04.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _setv(self, off, a):
        self.lock.acquire()
        for v in a:
            (f, i) = math.modf(v)  # split into fraction and integer
            f = int(round(f * 10000))  # we only need 3dp
            (l, h) = self.to_le(int(i))
            self.lcd_data[off] = l
            self.lcd_data[off + 1] = h
            (l, h) = self.to_le(f, v < 0)
            self.lcd_data[off + 2] = l
            self.lcd_data[off + 3] = h
            off += 4
        self.lock.release() 
Example 21
Project: inputs   Author: zeth   File: inputs.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_timeval(seconds_since_epoch):
    """Convert time into C style timeval."""
    frac, whole = math.modf(seconds_since_epoch)
    microseconds = math.floor(frac * 1000000)
    seconds = math.floor(whole)
    return seconds, microseconds 
Example 22
def microtime(get_as_float=False):
    if get_as_float:
        return time.time()
    else:
        return '%.8f %d' % math.modf(time.time()) 
Example 23
Project: prefactor   Author: lofar-astron   File: fits2sky.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ra2hhmmss(deg):
    """Convert RA coordinate (in degrees) to HH MM SS"""

    from math import modf
    if deg < 0:
        deg += 360.0
    x, hh = modf(deg/15.)
    x, mm = modf(x*60)
    ss = x*60

    return (int(hh), int(mm), ss) 
Example 24
Project: prefactor   Author: lofar-astron   File: fits2sky.py    License: GNU General Public License v3.0 5 votes vote down vote up
def dec2ddmmss(deg):
    """Convert DEC coordinate (in degrees) to DD MM SS"""

    from math import modf
    sign = (-1 if deg < 0 else 1)
    x, dd = modf(abs(deg))
    x, ma = modf(x*60)
    sa = x*60

    return (int(dd), int(ma), sa, sign) 
Example 25
Project: scorched   Author: lugensa   File: dates.py    License: MIT License 5 votes vote down vote up
def datetime_factory(**kwargs):
    second = kwargs.get('second')
    if second is not None:
        f, i = math.modf(second)
        kwargs['second'] = int(i)
        kwargs['microsecond'] = int(f * 1000000)
    try:
        return datetime.datetime(**kwargs)
    except ValueError as e:
        raise DateTimeRangeError(e.args[0]) 
Example 26
Project: android_rinex   Author: rokubun   File: gnsslogger.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def glot_to_gpst(gpst_current_epoch, tod_seconds):
    """
    Converts GLOT to GPST
    :param gpst_current_epoch: Current epoch of the measurement in GPST
    :param tod_seconds: Time of days as number of seconds
    :return: Time of week in seconds
    """
    (tod_sec_frac, tod_sec) = math.modf(tod_seconds)
    tod_sec = int(tod_sec)

    # Get the GLONASS epoch given the current GPS time
    glo_epoch = datetime.datetime(year=gpst_current_epoch.year,
                                  month=gpst_current_epoch.month,
                                  day=gpst_current_epoch.day,
                                  hour=gpst_current_epoch.hour,
                                  minute=gpst_current_epoch.minute,
                                  second=gpst_current_epoch.second)\
                                  + datetime.timedelta(
                                  hours=3,
                                  seconds=-CURRENT_GPS_LEAP_SECOND)
    # Adjust the GLONASS time with the TOD measurements
    glo_tod = datetime.datetime(year=glo_epoch.year,
                                month=glo_epoch.month,
                                day=glo_epoch.day) + datetime.timedelta(seconds=tod_sec)

    # The day of week in seconds needs to reflect the time passed before the current day starts
    day_of_week_sec = (glo_tod.isoweekday()) * DAYSEC

    # Compute time of week in seconds
    tow_sec = day_of_week_sec + tod_seconds - GLOT_TO_UTC + CURRENT_GPS_LEAP_SECOND

    return tow_sec

# ------------------------------------------------------------------------------ 
Example 27
Project: NXP-MCUBootFlasher   Author: JayHeng   File: uicore.py    License: Apache License 2.0 5 votes vote down vote up
def setCostTime( self, costTimeSec ):
        minValueStr = '00'
        secValueStr = '00'
        millisecValueStr = '000'
        if costTimeSec != 0:
            costTimeSecMod = math.modf(costTimeSec)
            minValue = int(costTimeSecMod[1] / 60)
            if minValue < 10:
                minValueStr = '0' + str(minValue)
            elif minValue <= 59:
                minValueStr = str(minValue)
            else:
                minValueStr = 'xx'
            secValue = int(costTimeSecMod[1]) % 60
            if secValue < 10:
                secValueStr = '0' + str(secValue)
            else:
                secValueStr = str(secValue)
            millisecValue = int(costTimeSecMod[0] * 1000)
            if millisecValue < 10:
                millisecValueStr = '00' + str(millisecValue)
            elif millisecValue < 100:
                millisecValueStr = '0' + str(millisecValue)
            else:
                millisecValueStr = str(millisecValue)
        self.m_staticText_costTime.SetLabel(' ' + minValueStr + ':' + secValueStr + '.' + millisecValueStr) 
Example 28
Project: PySpace   Author: HackerPoet   File: ray_marcher_demo.py    License: MIT License 5 votes vote down vote up
def interp_data(x, f=2.0):
	new_dim = int(x.shape[0]*f)
	output = np.empty((new_dim,) + x.shape[1:], dtype=np.float32)
	for i in range(new_dim):
		a, b1 = math.modf(float(i) / f)
		b2 = min(b1 + 1, x.shape[0] - 1)
		output[i] = x[int(b1)]*(1-a) + x[int(b2)]*a
	return output 
Example 29
Project: vnpy_crypto   Author: birforce   File: jdcal.py    License: MIT License 5 votes vote down vote up
def fpart(x):
    """Return fractional part of given number."""
    return math.modf(x)[0] 
Example 30
Project: vnpy_crypto   Author: birforce   File: jdcal.py    License: MIT License 5 votes vote down vote up
def ipart(x):
    """Return integer part of given number."""
    return math.modf(x)[1]