# 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 , or try the search function .
Example #1
```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 #2
```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 #3
```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 #4
```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
```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 #6
```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
```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 #8
```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 #9
```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 #10
```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
```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 #12
```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 #13
```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 #14
```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)
]
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
Example #15
```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 #16
```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 #17
```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)
]
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
Example #18
```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 #19
```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 #20
```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 #21
```def microtime(get_as_float=False):
if get_as_float:
return time.time()
else:
return '%.8f %d' % math.modf(time.time()) ```
Example #22
```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 #23
```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 #24
```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 #25
```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 #26
```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

# ------------------------------------------------------------------------------ ```
Example #27
```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
```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
```def fpart(x):
```def ipart(x):