Python math.modf() Examples

The following are 30 code examples of math.modf(). 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 File: test_math.py    From Fluid-Designer with 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 #2
Source File: test_math.py    From oss-ftp with 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 #3
Source File: cut.py    From winapi-deobfuscation with 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 #4
Source File: test_math.py    From gcblue with 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 #5
Source File: vector.py    From ezdxf with 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 #6
Source File: prep_noise.py    From Build-CNN-or-LSTM-or-CNNLSTM-with-speech-features with 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 #7
Source File: models.py    From BMN-Boundary-Matching-Network with 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 #8
Source File: models.py    From market_predictor_cnn with 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 #9
Source File: test_math.py    From BinderFilter with 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 #10
Source File: datetime.py    From Fluid-Designer with 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 #11
Source File: test_math.py    From ironpython2 with 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 #12
Source File: datetime.py    From Project-New-Reign---Nemesis-Main with 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 #13
Source File: test_math.py    From Project-New-Reign---Nemesis-Main with 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 #14
Source File: modeling.py    From hapi with 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 #15
Source File: test_math.py    From ironpython3 with 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 #16
Source File: datetime.py    From ironpython3 with 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 #17
Source File: utils.py    From bard with 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 #18
Source File: B13346_05_10-dd2dms.py    From Learning-Geospatial-Analysis-with-Python-Third-Edition with MIT License 6 votes vote down vote up
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 #19
Source File: daycycle.py    From piqueserver with GNU General Public License v3.0 5 votes vote down vote up
def day_time(connection, value=None):
    if value is not None:
        if not connection.admin:
            return S_NO_RIGHTS
        time = float(value)
        if time < 0.0:
            raise ValueError("Time cannot be < 0")
        connection.protocol.current_time = time
        connection.protocol.update_day_color()
    f, i = modf(connection.protocol.current_time)
    return S_TIME_OF_DAY.format(hours=int(i), minutes=int(f * 60)) 
Example #20
Source File: star.py    From pyem with GNU General Public License v3.0 5 votes vote down vote up
def recenter_modf(df, inplace=False):
    df = df if inplace else df.copy()
    remxy, offsetxy = np.vectorize(modf)(df[Relion.ORIGINS])
    df[Relion.ORIGINS] = remxy
    df[Relion.COORDS] = df[Relion.COORDS] - offsetxy
    return df 
Example #21
Source File: xcoin_api_client.py    From Coiner with Apache License 2.0 5 votes vote down vote up
def microtime(self, get_as_float = False):
        if get_as_float:
            return time.time()
        else:
            return '%f %d' % math.modf(time.time()) 
Example #22
Source File: exp.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def microtime(get_as_float = False) :
    if get_as_float:
        return time.time()
    else:
        return '%.8f %d' % math.modf(time.time()) 
Example #23
Source File: discuz_7_2_sqlinj.py    From PocHunter with MIT License 5 votes vote down vote up
def microtime(get_as_float=False):
        if get_as_float:
            return time.time()
        else:
            return '%.8f %d' % math.modf(time.time()) 
Example #24
Source File: cvrp_io.py    From VeRyPy with MIT License 5 votes vote down vote up
def _degrees_and_minutes_to_radians(x):
    """ Adapted from Reneilt 1991 TSPLIB article / TSPFAQ """
    PI = 3.141592
    mins, degs = modf(x)
    return (degs+100/60.0*mins)*PI/180.0 
Example #25
Source File: metrics.py    From suds-py3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __str__(self):
        if self.started == 0:
            return 'not-running'
        if self.started > 0 and self.stopped == 0:
            return 'started: %d (running)' % self.started
        duration = self.duration()
        jmod = lambda m: (m[1], m[0]*1000)
        if duration < 1:
            ms = (duration*1000)
            return '%d (ms)' % ms
        if duration < 60:
            m = modf(duration)
            return '%d.%.3d (seconds)' % jmod(m)
        m = modf(duration/60)
        return '%d.%.3d (minutes)' % jmod(m) 
Example #26
Source File: jdcal.py    From gxpy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ipart(x):
    """Return integer part of given number."""
    return math.modf(x)[1] 
Example #27
Source File: jdcal.py    From gxpy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fpart(x):
    """Return fractional part of given number."""
    return math.modf(x)[0] 
Example #28
Source File: common.py    From linux-kernel-module-cheat with GNU General Public License v3.0 5 votes vote down vote up
def seconds_to_hms(seconds):
        '''
        Seconds to hour:minute:seconds

        :ptype seconds: float
        :rtype: str

        https://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds 
        '''
        frac, whole = math.modf(seconds)
        hours, rem = divmod(whole, 3600)
        minutes, seconds = divmod(rem, 60)
        return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)) 
Example #29
Source File: uicore.py    From NXP-MCUBootUtility with 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 #30
Source File: logger.py    From fitlog with Apache License 2.0 5 votes vote down vote up
def set_rng_seed(self, rng_seed:int = None, random:bool = True, numpy:bool = True,
                     pytorch:bool=True, deterministic:bool=True):
        """
        设置模块的随机数种子。由于pytorch还存在cudnn导致的非deterministic的运行,所以一些情况下可能即使seed一样,结果也不一致
            需要在fitlog.commit()或fitlog.set_log_dir()之后运行才会记录该rng_seed到log中
        :param int rng_seed: 将这些模块的随机数设置到多少,默认为随机生成一个。
        :param bool, random: 是否将python自带的random模块的seed设置为rng_seed.
        :param bool, numpy: 是否将numpy的seed设置为rng_seed.
        :param bool, pytorch: 是否将pytorch的seed设置为rng_seed(设置torch.manual_seed和torch.cuda.manual_seed_all).
        :param bool, deterministic: 是否将pytorch的torch.backends.cudnn.deterministic设置为True
        """
        if rng_seed is None:
            import time
            import math
            rng_seed = int(math.modf(time.time())[0]*1000000)
        if random:
            import random
            random.seed(rng_seed)
        if numpy:
            try:
                import numpy
                numpy.random.seed(rng_seed)
            except:
                pass
        if pytorch:
            try:
                import torch
                torch.manual_seed(rng_seed)
                torch.cuda.manual_seed(rng_seed)
                torch.cuda.manual_seed_all(rng_seed)
                if deterministic:
                    torch.backends.cudnn.deterministic = True
            except:
                pass
        if self.initialized:
            self.add_other(rng_seed, 'rng_seed')
        os.environ['PYTHONHASHSEED'] = str(rng_seed)  # 为了禁止hash随机化,使得实验可复现。
        return rng_seed