本文整理汇总了Python中fractions.Fraction类的典型用法代码示例。如果您正苦于以下问题:Python Fraction类的具体用法?Python Fraction怎么用?Python Fraction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Fraction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _msec_to_numden
def _msec_to_numden(delay):
"""
delay is the time delay in milliseconds.
Return value is the tuple (delay_num, delay_den) representing
the delay in seconds as the fraction delay_num/delay_den.
Each value in the tuple is an integer less than 65536.
"""
if delay == 0:
return (0, 1)
# Convert delay to seconds.
delay = delay/1000.0
if delay > 1:
f = Fraction.from_float(1.0/delay).limit_denominator(65535)
num = f.denominator
den = f.numerator
else:
f = Fraction.from_float(delay).limit_denominator(65535)
num = f.numerator
den = f.denominator
if (num, den) == (1, 0):
raise ValueError("delay=%r is too large to convert to "
"delay_num/delay_den" % (delay,))
if (num, den) == (0, 1):
raise ValueError("delay=%r is too small to convert to "
"delay_num/delay_den" % (delay,))
return num, den
示例2: seleciona_Coeficientes
def seleciona_Coeficientes(matriz_Fxn, matriz):
print "\nPolinômio P"+str(colunas-1)+":"
fator = ""
for i in range(colunas):
for j in range(colunas):
#pula se der 0
if i==j and i==0:
print BOLD+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
#coeficiente diferente de 0
elif i==j:
#imprime a diferenca
if matriz[0][j-1] != 0.0:
if matriz[0][j-1] > 0.0:
fator += "(x-"+str(Fraction.from_float(abs(matriz[0][j-1])).limit_denominator(NUMERADOR))+")"
else:
fator += "(x+"+str(Fraction.from_float(abs(matriz[0][j-1])).limit_denominator(NUMERADOR))+")"
else:
fator += "(x)"
#coeficiente da matriz com sinal
if matriz_Fxn[i][j] > 0.0:
print BOLD+"+"+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
else:
print BOLD+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
print "\n"
示例3: variance
def variance(series, weights, mean):
"""Precisely calculates the variance of a series of floats
Note: uses N-1 as correction factor.
Note: assumes mean to be an instance of Fraction"""
if len(series) <> len(weights):
return float("NaN")
if not isinstance(mean, Fraction):
return float("NaN")
factor = Fraction(0)
total_weight = Fraction(-1)
i = 0
length = len(series)
while (i < length):
delta = Fraction.from_float(series[i]) - mean
weight = Fraction.from_float(weights[i])
factor += delta*delta*weight
total_weight += weight
i += 1
if total_weight <= 0:
return float("NaN")
return factor/total_weight
示例4: __init__
def __init__(self, infreq, outfreq):
self.clkin = Signal()
self.clkout = Signal()
ratio = Fraction(outfreq)/Fraction(infreq)
appr = ratio.limit_denominator(32)
m = appr.numerator
if m < 2 or m > 32:
raise OverflowError
d = appr.denominator
in_period = float(Fraction(1000000000)/Fraction(infreq))
self._inst = Instance("DCM_SP",
[("CLKFX", self.clkout)],
[("CLKIN", self.clkin),
("PSEN", BV(1)),
("RST", BV(1))],
[("CLKDV_DIVIDE", 2.0),
("CLKFX_DIVIDE", d),
("CLKFX_MULTIPLY", m),
("CLKIN_DIVIDE_BY_2", "FALSE"),
("CLKIN_PERIOD", in_period),
("CLKOUT_PHASE_SHIFT", "NONE"),
("CLK_FEEDBACK", "NONE"),
("DESKEW_ADJUST", "SYSTEM_SYNCHRONOUS"),
("DUTY_CYCLE_CORRECTION", "TRUE"),
("PHASE_SHIFT", 0),
("STARTUP_WAIT", "TRUE")]
)
示例5: to_frac
def to_frac(v):
v = Fraction(v)
v = v.limit_denominator(1000)
v = str(v)
if "/" in v:
v = v.split("/")
v = "\\frac{%s}{%s}" % (v[0], v[1])
return v
示例6: rational
def rational(arg, max_denominator=1000000):
# return nominator and denominator from float or two integers
try:
f = Fraction.from_float(arg)
except TypeError:
f = Fraction(arg[0], arg[1])
f = f.limit_denominator(max_denominator)
return f.numerator, f.denominator
示例7: solve
def solve(n, m):
total_cases = nCr(n+m, n)
failed_cases = fail(n, m)
from fractions import Fraction
f = Fraction(total_cases - failed_cases, total_cases)
f.limit_denominator()
return float(f)
示例8: output_dynamics
def output_dynamics(message):
i = struct.unpack("!dd", message)
acc_fr = Fraction(i[0])
acc_fr = acc_fr.limit_denominator(8)
brk_fr = Fraction(i[1])
brk_fr = brk_fr.limit_denominator(8)
return struct.pack("<hhhh", int(acc_fr.numerator), int(acc_fr.denominator),
int(brk_fr.numerator), int(brk_fr.denominator))
示例9: fraction_cheating
def fraction_cheating(n=3,d=7,limit = 1000000):
'''
find the reduced proper fraction directly
to the left of the given target
problem 71
'''
real = Fraction(n,d)
approx = Fraction(n/d)
while approx.limit_denominator(limit) == real: #Fraction(7720456504063707, 18014398509481984)
approx = Fraction(approx.numerator-1,approx.denominator)
return approx #Fraction(3595117, 8388608)???
示例10: data_averaging_coeffs
def data_averaging_coeffs(fh1, fh2):
"""
return the time-and-frequency averaging parameters
which help get the data on the same grid(s)
"""
## read the two filestreams in chunks of equal time
sr = Fraction(fh1.dtsample.to(u.s).value * fh1.blocksize
/ fh1.recordsize)
sr /= Fraction(fh2.dtsample.to(u.s).value * fh2.blocksize
/ fh2.recordsize)
sr = sr.limit_denominator(1000)
nf1 = sr.denominator
nf2 = sr.numerator
## used for re-sizing hdf5 x-corr output
raw1_nrows = int(fh1.blocksize * nf1 / fh1.recordsize)
raw2_nrows = int(fh2.blocksize * nf2 / fh2.recordsize)
## time averaging params
Tavg = Fraction(raw1_nrows, raw2_nrows).limit_denominator(1000)
Tden = Tavg.denominator
Tnum = Tavg.numerator
## channel averaging params
f1info = (fh1.freq.max(), fh1.freq.min(), len(fh1.freq),
np.sign(np.diff(fh1.freq).mean()))
f2info = (fh2.freq.max(), fh2.freq.min(), len(fh2.freq),
np.sign(np.diff(fh2.freq).mean()))
f1keep = (fh1.freq > max(f1info[1], f2info[1])) \
& (fh1.freq < min(f1info[0], f2info[0]))
f2keep = (fh2.freq > max(f1info[1], f2info[1])) \
& (fh2.freq < min(f1info[0], f2info[0]))
Favg = abs(Fraction(np.diff(fh1.freq.value).mean()
/ np.diff(fh2.freq.value).mean()))
Favg = Favg.limit_denominator(200)
Fden = Favg.denominator
Fnum = Favg.numerator
# the frequencies we keep
freq1 = fh1.freq[f1keep]
freq1 = freq1.reshape(freq1.size / Fden, Fden).mean(axis=-1)
freq2 = fh2.freq[f2keep]
freq2 = freq2.reshape(freq2.size / Fnum, Fnum).mean(axis=-1)
# sort low freq to high freq
if f1info[3] < 0:
freq1 = freq1[::-1]
if f2info[3] < 0:
freq2 = freq2[::-1]
return ((nf1, nf2), (Tnum, Tden), (Fden, Fnum), (f1keep, f2keep),
(freq1, freq2), (raw1_nrows, raw2_nrows))
示例11: test_createNodeWithInitialValue
def test_createNodeWithInitialValue(self):
"""
Generates 100 random values from -1 to 2 and creates nodes with them as
initial values. Checks, that for values below zero and above one a
ValueError is raised.
:return:
"""
for val in [self.rand.uniform(-1, 2) for _ in range(100)]:
if val < 0 or val > 1:
with self.assertRaises(ValueError):
Node(Fraction.from_float(val))
else:
node = Node(Fraction.from_float(val))
self.assertEqual(val, node.initial_value)
self.assertEqual(val, node.value)
示例12: test_fireCycles
def test_fireCycles(self):
"""
Generates a list of nodes and weights, and a test node and their initial
value. Then adds the list as cycle_successors to the node and calls
fire.
Checks that all values are calculated correctly.
Also checks that firing multiple times sums the values.
:return:
"""
# TODO: check for transformation function
value_list = [self.rand.uniform(0, 1) for _ in range(100)]
node_list = [
(CycleNode(float(Fraction(0))), Fraction.from_float(val))
for val in value_list
]
test_node = CycleNode(float(Fraction(0)), float(Fraction(1, 2)))
test_node.add_successors(node_list)
# Creates a copy of the node list and manually calculates their values
# after firing the test node
fired_node_list = node_list.copy()
for node, value in fired_node_list:
node.add_value(0.5 * value)
test_node.fire()
self.assertListEqual(node_list, fired_node_list)
示例13: test_addSuccessor
def test_addSuccessor(self):
"""
Generates 100 random values from -1 to 2. Creates new nodes for every
value and adds them using the generated value as the weight.
Checks, that for values below zero and above one a
ValueError is raised.
:return:
"""
test_node = Node()
for val in [self.rand.uniform(-1, 2) for _ in range(100)]:
new_node = Node()
if val < 0 or val > 1:
with self.assertRaises(ValueError):
test_node.add_successor(new_node, Fraction.from_float(val))
else:
test_node.add_successor(new_node, Fraction.from_float(val))
示例14: rep_as_fraction
def rep_as_fraction(self):
frac = Fraction.from_float(self.radius)
whole = int(frac.numerator)/int(frac.denominator)
remainder = int(frac.numerator)%int(frac.denominator)
self.rational_num = str(whole) + " " + str(remainder) + "/" + str(frac.denominator)
示例15: __init__
def __init__(self, *args):
self.value = Fraction(*args).limit_denominator()
super(Rational, self).__init__()
self.numerator = self.value.numerator
self.denominator = self.value.denominator