Python fractions.Fraction() Examples
The following are 30
code examples of fractions.Fraction().
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
fractions
, or try the search function
.
Example #1
Source File: pi-timolo.py From pi-timolo with MIT License | 6 votes |
def getStreamImage(isDay): # Capture an image stream to memory based on daymode with picamera.PiCamera() as camera: camera.resolution = (testWidth, testHeight) with picamera.array.PiRGBArray(camera) as stream: if isDay: camera.exposure_mode = 'auto' camera.awb_mode = 'auto' time.sleep(motionCamSleep) # sleep so camera can get AWB else: # use variable framerate_range for Low Light motion image stream camera.framerate_range = (Fraction(1, 6), Fraction(30, 1)) time.sleep(2) # Give camera time to measure AWB camera.iso = nightMaxISO camera.capture(stream, format='rgb', use_video_port=useVideoPort) camera.close() return stream.array #-----------------------------------------------------------------------------------------------
Example #2
Source File: teaching_equivalents_inst.py From coursys with GNU General Public License v3.0 | 6 votes |
def edit_teaching_equivalent_inst(request, equivalent_id): """ Instructors form to edit a teaching equivalent """ instructor = get_object_or_404(Person, userid=request.user.username) equivalent = get_object_or_404(TeachingEquivalent, pk=equivalent_id, instructor=instructor, status='UNCO') if request.method == 'POST': form = TeachingEquivForm(request.POST, instance=equivalent) if form.is_valid(): equivalent = form.save(commit=False) equivalent.credits_numerator = form.cleaned_data['credits_numerator'] equivalent.credits_denominator = form.cleaned_data['credits_denominator'] equivalent.save() messages.add_message(request, messages.SUCCESS, "Teaching Equivalent successfully edited") return HttpResponseRedirect(reverse('planning.views.view_teaching_equivalent_inst', kwargs={'equivalent_id': equivalent.id})) else: credits_value = Fraction("%d/%d" % (equivalent.credits_numerator, equivalent.credits_denominator)).__str__() form = TeachingEquivForm(instance=equivalent, initial={'credits': credits_value}) return render(request, 'planning/edit_teaching_equiv_inst.html', {'form': form, 'equivalent': equivalent})
Example #3
Source File: teaching_equivalents_admin.py From coursys with GNU General Public License v3.0 | 6 votes |
def edit_course_offering_credits(request, userid, course_slug): """ Edit the amount of credits a course offering is worth """ instructor = _get_instructor_for_units(request, userid) member = get_object_or_404(Member, role='INST', person=instructor, offering__slug=course_slug) if request.method == 'POST': form = CourseOfferingCreditForm(request.POST) if form.is_valid(): member.set_teaching_credit(form.cleaned_data['credits']) member.save() messages.add_message(request, messages.SUCCESS, "Course credits successfully updated for %s" % member.offering.name()) return HttpResponseRedirect(reverse('planning.views.view_teaching_credits_admin', kwargs={'userid': userid})) else: form = CourseOfferingCreditForm(initial={'credits': Fraction(member.teaching_credit()).__str__()}) return render(request, 'planning/edit_offering_credits.html', {'form': form, 'instructor': instructor, 'member': member})
Example #4
Source File: test_fractions.py From ironpython2 with Apache License 2.0 | 6 votes |
def testInit(self): self.assertEqual((0, 1), _components(F())) self.assertEqual((7, 1), _components(F(7))) self.assertEqual((7, 3), _components(F(F(7, 3)))) self.assertEqual((-1, 1), _components(F(-1, 1))) self.assertEqual((-1, 1), _components(F(1, -1))) self.assertEqual((1, 1), _components(F(-2, -2))) self.assertEqual((1, 2), _components(F(5, 10))) self.assertEqual((7, 15), _components(F(7, 15))) self.assertEqual((10**23, 1), _components(F(10**23))) self.assertEqual((3, 77), _components(F(F(3, 7), 11))) self.assertEqual((-9, 5), _components(F(2, F(-10, 9)))) self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113)))) self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)", F, 12, 0) self.assertRaises(TypeError, F, 1.5 + 3j) self.assertRaises(TypeError, F, "3/2", 3) self.assertRaises(TypeError, F, 3, 0j) self.assertRaises(TypeError, F, 3, 1j)
Example #5
Source File: test_fractions.py From ironpython2 with Apache License 2.0 | 6 votes |
def testFromDecimal(self): self.assertRaises(TypeError, F.from_decimal, 3+4j) self.assertEqual(F(10, 1), F.from_decimal(10)) self.assertEqual(F(0), F.from_decimal(Decimal("-0"))) self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5"))) self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3"))) self.assertEqual(F(5000), F.from_decimal(Decimal("5e3"))) self.assertEqual(1 - F(1, 10**30), F.from_decimal(Decimal("0." + "9" * 30))) self.assertRaisesMessage( TypeError, "Cannot convert Infinity to Fraction.", F.from_decimal, Decimal("inf")) self.assertRaisesMessage( TypeError, "Cannot convert -Infinity to Fraction.", F.from_decimal, Decimal("-inf")) self.assertRaisesMessage( TypeError, "Cannot convert NaN to Fraction.", F.from_decimal, Decimal("nan")) self.assertRaisesMessage( TypeError, "Cannot convert sNaN to Fraction.", F.from_decimal, Decimal("snan"))
Example #6
Source File: event_display.py From coursys with GNU General Public License v3.0 | 6 votes |
def fraction_display(val): val = fractions.Fraction(val) n = val.numerator d = val.denominator if n != 0: whole = abs(n)/d*(n/abs(n)) # in case val is negative else: whole = 0 res = str(whole) # only have a negative fraction if whole is 0 if val<0 and whole==0: remainder = val + whole else: remainder = abs(val - whole) if remainder != 0: if whole == 0: res = str(remainder) else: res += ' ' + str(remainder) return res
Example #7
Source File: teaching_equivalents_admin.py From coursys with GNU General Public License v3.0 | 6 votes |
def edit_teaching_equivalent_admin(request, userid, equivalent_id): """ Edit a teaching equivalent for an instructor """ instructor = _get_instructor_for_units(request, userid) equivalent = get_object_or_404(TeachingEquivalent, pk=equivalent_id, instructor=instructor) if request.method == 'POST': form = TeachingEquivForm(request.POST, instance=equivalent) if form.is_valid(): equivalent = form.save(commit=False) equivalent.credits_numerator = form.cleaned_data['credits_numerator'] equivalent.credits_denominator = form.cleaned_data['credits_denominator'] equivalent.save() messages.add_message(request, messages.SUCCESS, "Teaching Equivalent successfully edited") return HttpResponseRedirect(reverse('planning.views.view_teaching_equivalent_admin', kwargs={'userid': userid, 'equivalent_id': equivalent.id})) else: credits_value = Fraction("%d/%d" % (equivalent.credits_numerator, equivalent.credits_denominator)).__str__() form = TeachingEquivForm(instance=equivalent, initial={'credits': credits_value}) return render(request, 'planning/edit_teaching_equiv_admin.html', {'form': form, 'equivalent': equivalent, 'instructor': instructor})
Example #8
Source File: test_arraypad.py From recruit with Apache License 2.0 | 6 votes |
def test_object_array(self): from fractions import Fraction arr = np.array([Fraction(1, 2), Fraction(-1, 2)]) actual = np.pad(arr, (2, 3), mode='linear_ramp', end_values=0) # deliberately chosen to have a non-power-of-2 denominator such that # rounding to floats causes a failure. expected = np.array([ Fraction( 0, 12), Fraction( 3, 12), Fraction( 6, 12), Fraction(-6, 12), Fraction(-4, 12), Fraction(-2, 12), Fraction(-0, 12), ]) assert_equal(actual, expected)
Example #9
Source File: test_state.py From pyquarkchain with MIT License | 6 votes |
def main(): global fixtures, filename, tests, testname, testdata parser = argparse.ArgumentParser() parser.add_argument("fixtures", type=str, help="fixture file path to run tests") args = parser.parse_args() qkc_env = DEFAULT_ENV.copy() # disable root chain tax qkc_env.quark_chain_config.REWARD_TAX_RATE = Fraction(0) # load fixtures from specified file or dir fixtures = testutils.get_tests_from_file_or_dir(args.fixtures) for filename, tests in list(fixtures.items()): for testname, testdata in list(tests.items()): if exclude_func(filename, None, None): print("Skipping: %s %s" % (filename, testname)) continue print("Testing: %s %s" % (filename, testname)) # hack qkc env into the test testdata["qkc"] = qkc_env testdata["qkcstate"] = "QuarkChainStateTests" in filename testdata["testname"] = testname testdata["filename"] = filename checker(testdata)
Example #10
Source File: test_inference.py From recruit with Apache License 2.0 | 6 votes |
def test_is_scalar_builtin_scalars(self): assert is_scalar(None) assert is_scalar(True) assert is_scalar(False) assert is_scalar(Number()) assert is_scalar(Fraction()) assert is_scalar(0.) assert is_scalar(np.nan) assert is_scalar('foobar') assert is_scalar(b'foobar') assert is_scalar(u('efoobar')) assert is_scalar(datetime(2014, 1, 1)) assert is_scalar(date(2014, 1, 1)) assert is_scalar(time(12, 0)) assert is_scalar(timedelta(hours=1)) assert is_scalar(pd.NaT)
Example #11
Source File: processchemistry.py From burnman with GNU General Public License v2.0 | 6 votes |
def dictionarize_formula(formula): """ A function to read a chemical formula string and convert it into a dictionary """ f = dict() elements = re.findall('[A-Z][^A-Z]*', formula) for element in elements: element_name = re.split('[0-9][^A-Z]*', element)[0] element_atoms = re.findall('[0-9][^A-Z]*', element) if len(element_atoms) == 0: element_atoms = Fraction(1.0) else: element_atoms = Fraction(element_atoms[0]) f[element_name] = f.get(element_name, 0.0) + element_atoms return f
Example #12
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_get(self): p = Palette([Red, Green, Blue], continuous=True) result = [p(-1 + Fraction(i) / 2) for i in range(12)] expected = [ (0, 170, 85), (0, 85, 170), (255, 0, 0), (170, 85, 0), (85, 170, 0), (0, 255, 0), (0, 170, 85), (0, 85, 170), (255, 0, 0), (170, 85, 0), (85, 170, 0), (0, 255, 0)] self.assertEqual(result, expected)
Example #13
Source File: compression_based.py From textdistance with MIT License | 6 votes |
def _make_probs(self, *sequences): """ https://github.com/gw-c/arith/blob/master/arith.py """ sequences = self._get_counters(*sequences) counts = self._sum_counters(*sequences) if self.terminator is not None: counts[self.terminator] = 1 total_letters = sum(counts.values()) prob_pairs = {} cumulative_count = 0 counts = sorted(counts.items(), key=lambda x: (x[1], x[0]), reverse=True) for char, current_count in counts: prob_pairs[char] = ( Fraction(cumulative_count, total_letters), Fraction(current_count, total_letters), ) cumulative_count += current_count assert cumulative_count == total_letters return prob_pairs
Example #14
Source File: utils.py From pi-timolo with MIT License | 6 votes |
def match_string(string): """Match a string against the expected format for a :class:`Fraction` (``[-]numerator/denominator``) and return the numerator and denominator as a tuple. Args: string -- a string representation of a rational number Return: a tuple (numerator, denominator) Raise ValueError: if the format of the string is invalid """ format_re = re.compile(r'(?P<numerator>-?\d+)/(?P<denominator>\d+)') match = format_re.match(string) if match is None: raise ValueError('Invalid format for a rational: %s' % string) gd = match.groupdict() return (int(gd['numerator']), int(gd['denominator']))
Example #15
Source File: pi-timolo81.py From pi-timolo with MIT License | 6 votes |
def getStreamImage(isDay): # Capture an image stream to memory based on daymode with picamera.PiCamera() as camera: camera.resolution = (testWidth, testHeight) with picamera.array.PiRGBArray(camera) as stream: if isDay: camera.exposure_mode = 'auto' camera.awb_mode = 'auto' time.sleep(motionCamSleep) # sleep so camera can get AWB else: # use variable framerate_range for Low Light motion image stream camera.framerate_range = (Fraction(1, 6), Fraction(30, 1)) time.sleep(2) # Give camera time to measure AWB camera.iso = nightMaxISO camera.capture(stream, format='rgb', use_video_port=useVideoPort) camera.close() return stream.array #-----------------------------------------------------------------------------------------------
Example #16
Source File: utils.py From pi-timolo with MIT License | 6 votes |
def make_fraction(*args): """Make a fraction. Raise TypeError: if the arguments do not match the expected format for a fraction """ if len(args) == 1: numerator, denominator = match_string(args[0]) elif len(args) == 2: numerator = args[0] denominator = args[1] else: raise TypeError('Invalid format for a fraction: %s' % str(args)) if denominator == 0 and numerator == 0: # Null rationals are often stored as '0/0'. # We want to be fault-tolerant in this specific case # (see https://bugs.launchpad.net/pyexiv2/+bug/786253). denominator = 1 return Fraction(numerator, denominator)
Example #17
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_continuous_serpentine(self): colors = [Red, Green, Blue, White] p = Palette(colors, serpentine=True, continuous=True) result = [p(-1 + Fraction(i) / 3) for i in range(15)] expected = [ (63.75, 191.25, 0.0), (127.5, 127.5, 0.0), (191.25, 63.75, 0.0), (255.0, 0.0, 0.0), (191.25, 63.75, 0.0), (127.5, 127.5, 0.0), (63.75, 191.25, 0.0), (0.0, 255.0, 0.0), (0.0, 191.25, 63.75), (0.0, 127.5, 127.5), (0.0, 63.75, 191.25), (0.0, 0.0, 255.0), (63.75, 63.75, 255.0), (127.5, 127.5, 255.0), (191.25, 191.25, 255.0) ] self.assertEqual(expected, result)
Example #18
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_continuous(self): colors = [Red, Green, Blue, White] p = Palette(colors, continuous=True) result = [p(-1 + Fraction(i) / 3) for i in range(16)] expected = [ (63.75, 63.75, 255.0), (127.5, 127.5, 255.0), (191.25, 191.25, 255.0), (255.0, 0.0, 0.0), (191.25, 63.75, 0.0), (127.5, 127.5, 0.0), (63.75, 191.25, 0.0), (0.0, 255.0, 0.0), (0.0, 191.25, 63.75), (0.0, 127.5, 127.5), (0.0, 63.75, 191.25), (0.0, 0.0, 255.0), (63.75, 63.75, 255.0), (127.5, 127.5, 255.0), (191.25, 191.25, 255.0), (255.0, 0.0, 0.0), ] self.assertEqual(expected, result)
Example #19
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_double_serpentine(self): p = Palette([Red, Green], serpentine=True, continuous=True) result = [p(-1 + Fraction(i) / 3) for i in range(12)] expected = [ (127.5, 127.5, 0.0), (170.0, 85.0, 0.0), (212.5, 42.5, 0.0), (255.0, 0.0, 0.0), (212.5, 42.5, 0.0), (170.0, 85.0, 0.0), (127.5, 127.5, 0.0), (85.0, 170.0, 0.0), (42.5, 212.5, 0.0), (0.0, 255.0, 0.0), (42.5, 212.5, 0.0), (85.0, 170.0, 0.0) ] self.assertEqual(result, expected)
Example #20
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_double(self): p = Palette([Red, Green], continuous=True) self.assertEqual(p[0], Red) self.assertEqual(p[1], Green) result = [p(-1 + Fraction(i) / 3) for i in range(12)] expected = [ (127.5, 127.5, 0), (85, 170, 0), (42.5, 212.5, 0), (255, 0, 0), (212.5, 42.5, 0), (170, 85, 0), (127.5, 127.5, 0), (85, 170, 0), (42.5, 212.5, 0), (255, 0, 0), (212.5, 42.5, 0), (170, 85, 0) ] self.assertEqual(result, expected)
Example #21
Source File: palette_test.py From BiblioPixel with MIT License | 6 votes |
def test_get_serpentine(self): p = Palette([Red, Green, Blue], serpentine=True, continuous=True) result = [p(-1 + Fraction(i) / 2) for i in range(12)] expected = [ (85, 170, 0), (170, 85, 0), (255, 0, 0), (170, 85, 0), (85, 170, 0), (0, 255, 0), (0, 170, 85), (0, 85, 170), (0, 0, 255), (0, 85, 170), (0, 170, 85), (0, 255, 0) ] self.assertEqual(result, expected)
Example #22
Source File: limit_test.py From BiblioPixel with MIT License | 6 votes |
def test_colors(self): limit = Limit( ratio=Fraction(3, 4), knee=Fraction(1, 4), gain=Fraction(1, 2)) self.assertTrue(limit) cl = color_list_test.COLORS1[:] limit.limit_colors(cl, ListMath) c = 106 + 1 / 4 expected = [(c, 0, 0), (0, c, 0), (0, 0, c), (c, c, c)] self.assertEqual(len(expected), len(cl)) asserts = 0 for exp, act in zip(expected, cl): for e, a in zip(exp, act): self.assertAlmostEqual(e, a) asserts += 1 self.assertEqual(asserts, 12)
Example #23
Source File: test_float.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_floatasratio(self): for f, ratio in [ (0.875, (7, 8)), (-0.875, (-7, 8)), (0.0, (0, 1)), (11.5, (23, 2)), ]: self.assertEqual(f.as_integer_ratio(), ratio) for i in range(10000): f = random.random() f *= 10 ** random.randint(-100, 100) n, d = f.as_integer_ratio() self.assertEqual(float(n).__truediv__(d), f) R = fractions.Fraction self.assertEqual(R(0, 1), R(*float(0.0).as_integer_ratio())) self.assertEqual(R(5, 2), R(*float(2.5).as_integer_ratio())) self.assertEqual(R(1, 2), R(*float(0.5).as_integer_ratio())) self.assertEqual(R(4728779608739021, 2251799813685248), R(*float(2.1).as_integer_ratio())) self.assertEqual(R(-4728779608739021, 2251799813685248), R(*float(-2.1).as_integer_ratio())) self.assertEqual(R(-2100, 1), R(*float(-2100.0).as_integer_ratio())) self.assertRaises(OverflowError, float('inf').as_integer_ratio) self.assertRaises(OverflowError, float('-inf').as_integer_ratio) self.assertRaises(ValueError, float('nan').as_integer_ratio)
Example #24
Source File: palette_test.py From BiblioPixel with MIT License | 5 votes |
def test_autoscale(self): colors = [Red, Green, Blue, White] p = Palette(colors, autoscale=True) expected = [Red, Red, Green, Green, Blue, Blue, White, White, Red, Red] result = [p(Fraction(i) / 2) for i in range(10)] self.assertEqual(expected, result) p.length = 256 result = [p(32 * i) for i in range(10)] self.assertEqual(expected, result)
Example #25
Source File: test_fractions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testFromFloat(self): self.assertRaises(TypeError, F.from_float, 3+4j) self.assertEqual((10, 1), _components(F.from_float(10))) bigint = 1234567890123456789 self.assertEqual((bigint, 1), _components(F.from_float(bigint))) self.assertEqual((0, 1), _components(F.from_float(-0.0))) self.assertEqual((10, 1), _components(F.from_float(10.0))) self.assertEqual((-5, 2), _components(F.from_float(-2.5))) self.assertEqual((99999999999999991611392, 1), _components(F.from_float(1e23))) self.assertEqual(float(10**23), float(F.from_float(1e23))) self.assertEqual((3602879701896397, 1125899906842624), _components(F.from_float(3.2))) self.assertEqual(3.2, float(F.from_float(3.2))) inf = 1e1000 nan = inf - inf self.assertRaisesMessage( TypeError, "Cannot convert inf to Fraction.", F.from_float, inf) self.assertRaisesMessage( TypeError, "Cannot convert -inf to Fraction.", F.from_float, -inf) self.assertRaisesMessage( TypeError, "Cannot convert nan to Fraction.", F.from_float, nan)
Example #26
Source File: test-the-untestable.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 5 votes |
def test_mean_properties(data, type_, strat): strat = strat or st.from_type(type_) values = data.draw(st.lists(strat, min_size=1)) result = mean(values) # already testing no exceptions! # TODO: property assertions, e.g. bounds on result, etc. if type_ is Fraction: assert min(values) <= result <= max(values) # What constraints make sense for an integer mean? # TODO: metamorphic test assertions. For example, how should result # change if you add the mean to values? a number above or below result? # Remove some elements from values?
Example #27
Source File: test-the-untestable.py From escape-from-automanual-testing with GNU Affero General Public License v3.0 | 5 votes |
def mean(data, as_type=Fraction): """Return the mean of the input list, as the given type.""" # This function is a correct implementation of the arithmetic mean, # so that you can test it according to the metamorphic properties of # that mathematical equation for integers, floats, and fractions. assert as_type in (int, float, Fraction), as_type if as_type == int: return sum(int(n) for n in data) // len(data) # integer division case return sum(as_type(n) for n in data) / len(data) # float or Fraction case # You can use parametrize and given together, but two tips for best results: # 1. Put @parametrize *outside* @given - it doesn't work properly from the inside # 2. Use named arguments to @given - avoids confusing or colliding positional arguments
Example #28
Source File: test_transcoding.py From eventsourcing with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fraction_type(self): value = Fraction encoded = '{"__type__":"fractions#Fraction"}' self.assertTranscoding(value, encoded)
Example #29
Source File: test_float.py From segpy with GNU Affero General Public License v3.0 | 5 votes |
def test_zero_from_real_fraction(self): zero = IBMFloat.from_real(Fraction(0, 1)) assert zero.is_zero()
Example #30
Source File: test_transcoding.py From eventsourcing with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fraction(self): value = Fraction(1, 3) encoded = ( '{"__class__":{"state":{"_denominator":3,"_numerator":1},' '"topic":"fractions#Fraction"}}' ) self.assertTranscoding(value, encoded)