format_common.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2017 Mycroft AI Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 
18 
19 def convert_to_mixed_fraction(number, denominators):
20  """
21  Convert floats to components of a mixed fraction representation
22 
23  Returns the closest fractional representation using the
24  provided denominators. For example, 4.500002 would become
25  the whole number 4, the numerator 1 and the denominator 2
26 
27  Args:
28  number (float): number for convert
29  denominators (iter of ints): denominators to use, default [1 .. 20]
30  Returns:
31  whole, numerator, denominator (int): Integers of the mixed fraction
32  """
33  int_number = int(number)
34  if int_number == number:
35  return int_number, 0, 1 # whole number, no fraction
36 
37  frac_number = abs(number - int_number)
38  if not denominators:
39  denominators = range(1, 21)
40 
41  for denominator in denominators:
42  numerator = abs(frac_number) * denominator
43  if abs(numerator - round(numerator)) < 0.01: # 0.01 accuracy
44  break
45  else:
46  return None
47 
48  return int_number, int(round(numerator)), denominator
def convert_to_mixed_fraction(number, denominators)


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40