ROS Code
 All Classes Namespaces Files Functions Variables
maths.py
Go to the documentation of this file.
1 # Math modules
2 import math
3 import operator
4 import statistics
5 import random
6 import string
7 
8 from .roserrors import *
9 
10 # Automatically solve a simple maths problem
11 
12 
13 def autosolve(equation):
14  try:
15  num1 = int(equation.split(" ")[0])
16  except ValueError:
17  num1 = float(equation.split(" ")[0])
18  try:
19  num2 = int(equation.split(" ")[2])
20  except ValueError:
21  num2 = float(equation.split(" ")[2])
22  if equation.split(" ")[1] in ["+", "plus", "add"]:
23  return num1 + num2
24  elif equation.split(" ")[1] in ["-", "minus", "subtract"]:
25  return num1 - num2
26  elif equation.split(" ")[1] in ["*", "times", "multiply"]:
27  return num1 * num2
28  elif equation.split(" ")[1] in ["/", "divide", "quotient"]:
29  return num1 / num2
30  elif equation.split(" ")[1] in ["%", "remainder", "rem"]:
31  return num1 % num2
32 
33 
34 # Automatically solve a hard maths problem
35 
36 
37 def autohard(equation):
38  try:
39  num1 = int(equation.split(" ")[1])
40  except ValueError:
41  num1 = float(equation.split(" ")[1])
42  if equation.split(" ")[0] == "log":
43  return math.log(num1)
44  elif equation.split(" ")[0] == "acos":
45  return math.acos(num1)
46  elif equation.split(" ")[0] == "asin":
47  return math.asin(num1)
48  elif equation.split(" ")[0] == "atan":
49  return math.atan(num1)
50  elif equation.split(" ")[0] == "cos":
51  return math.cos(num1)
52  elif equation.split(" ")[0] == "hypot":
53  try:
54  num2 = int(equation.split(" ")[2])
55  except ValueError:
56  num2 = float(equation.split(" ")[2])
57  return math.hypot(num1, num2)
58  elif equation.split(" ")[0] == "sin":
59  return math.sin(num1)
60  elif equation.split(" ")[0] == "tan":
61  return math.tan(num1)
62 
63 
64 # Solve a simple maths equation manually (May be deprecated)
65 
66 
67 def equation(operation, firstnum, secondnum):
68  if not isnum(firstnum) and isnum(secondnum):
69  raise RuntimeError(
70  'An Error Has Occured: One Of The Values Specified Is Not A Number (0002)'
71  )
72  if operation == 'plus':
73  return (firstnum + secondnum)
74  elif operation == 'minus':
75  return (firstnum - secondnum)
76  elif operation == 'multiply':
77  return (firstnum * secondnum)
78  elif operation == 'divide':
79  if not secondnum == 0:
80  return (firstnum / secondnum)
81  else:
82  raise RuntimeError(
83  'An Error Has Occured: You Entered An Invalid Operation (0003)')
84 
85 
86 # Solve scientific operations manually (May be deprecated)
87 
88 
89 def scientific(number, operation, number2=None, logbase=10):
90  if operation == 'log':
91  return math.log(number, logbase)
92  elif operation == 'acos':
93  return math.acos(number)
94  elif operation == 'asin':
95  return math.asin(number)
96  elif operation == 'atan':
97  return math.atan(number)
98  elif operation == 'cos':
99  return math.cos(number)
100  elif operation == 'hypot':
101  return math.hypot(number, number2)
102  elif operation == 'sin':
103  return math.sin(number)
104  elif operation == 'tan':
105  return math.tan(number)
106 
107 
108 # Simplify A Fraction
109 
110 
111 def fracsimplify(numerator, denominator):
112  if numerator == denominator:
113  return '1/1'
114  elif numerator > denominator:
115  limit = int(numerator / 2)
116  elif numerator < denominator:
117  limit = int(denominator / 2)
118  for i in range(2, limit):
119  checknum = limit - i
120  if numerator % checknum == 0 and denominator % checknum == 0:
121  numerator = numerator / checknum
122  denominator = denominator / checknum
123  return str(int(numerator)) + '/' + str(int(denominator))
124 
125 
126 # Convert A Circle Measurement
127 
128 
129 def circleconvert(amount, currentformat, newformat):
130  currentformat = currentformat.lower()
131  newformat = newformat.lower()
132  if currentformat == newformat:
133  return amount
134  if currentformat == 'radius':
135  if newformat == 'diameter':
136  return amount * 2
137  elif newformat == 'circumference':
138  return amount * 2 * math.pi
139  elif currentformat == 'diameter':
140  if newformat == 'radius':
141  return amount / 2
142  elif newformat == 'circumference':
143  return amount * math.pi
144  elif currentformat == 'circumference':
145  if newformat == 'radius':
146  return amount / math.pi / 2
147  elif newformat == 'diameter':
148  return amount / math.pi
149 
150 
151 # Get The Amount Of Numbers Divisible By A Number
152 
153 
154 def amountdiv(number, minnum, maxnum):
155  amount = 0
156  for i in range(minnum, maxnum + 1):
157  if number % i == 0:
158  amount += 1
159  return amount
160 
161 
162 # Get A Constant
163 
164 
165 def constant(constanttype):
166  constanttype = constanttype.lower()
167  if constanttype == 'pi':
168  return math.pi
169  elif constanttype == 'e':
170  return math.e
171  elif constanttype == 'tau':
172  return math.tau
173  elif constanttype == 'inf':
174  return math.inf
175  elif constanttype == 'nan':
176  return math.nan
177  elif constanttype in ['phi', 'golden']:
178  return (1 + 5**0.5) / 2
179 
180 
181 # Find The Power Of A Number
182 
183 
184 def power(number, power):
185  return math.pow(number, power)
186 
187 
188 # Find The Square Root Of A number
189 
190 
191 def squareroot(number):
192  return math.sqrt(number)
193 
194 
195 # Find the factorial of a number
196 
197 
198 def factorial(n):
199  if n == 0:
200  return 1
201  return n * factorial(n - 1)
202 
203 
204 # Do An Average Command
205 
206 
207 def average(numbers, averagetype='mean'):
208  averagetype = averagetype.lower()
209  try:
210  statistics.mean(numbers)
211  except BaseException:
212  raise RuntimeError('An Error Has Occured: List Not Specified (0018)')
213  if averagetype == 'mean':
214  return statistics.mean(numbers)
215  elif averagetype == 'mode':
216  return statistics.mode(numbers)
217  elif averagetype == 'median':
218  return statistics.median(numbers)
219  elif averagetype == 'min':
220  return min(numbers)
221  elif averagetype == 'max':
222  return max(numbers)
223  elif averagetype == 'range':
224  return max(numbers) - min(numbers)
225  else:
226  raise RuntimeError(
227  'An Error Has Occured: You Entered An Invalid Operation (0003)')
228 
229 
230 # Check If A Number Is A Type
231 
232 
233 def numprop(value, propertyexpected):
234  if propertyexpected == 'triangular':
235  x = (math.sqrt(8 * value + 1) - 1) / 2
236  return bool(x - int(x) > 0)
237  elif propertyexpected == 'square':
238  return math.sqrt(value).is_integer()
239  elif propertyexpected == 'cube':
240  x = value**(1 / 3)
241  x = int(round(x))
242  return bool(x**3 == value)
243  elif propertyexpected == 'even':
244  return value % 2 == 0
245  elif propertyexpected == 'odd':
246  return not value % 2 == 0
247  elif propertyexpected == 'positive':
248  return bool(value > 0)
249  elif propertyexpected == 'negative':
250  return bool(value < 0)
251  elif propertyexpected == 'zero':
252  return bool(value == 0)
253 
254 
255 # Toggle A Number Between Positive And Negative
256 
257 
258 def posnegtoggle(number):
259  if bool(number > 0):
260  return number - number * 2
261  elif bool(number < 0):
262  return number + abs(number) * 2
263  elif bool(number == 0):
264  return number
265 
266 
267 # Check If A Variable Is Infinite
268 
269 
270 def isinfinite(variable):
271  return bool(math.isfinite(variable))
272 
273 
274 # Check if a variable is essetially "False"
275 
276 
277 def isfalse(variable):
278  if variable in [0, 0.0, False, [], {}, math.nan, ""]:
279  return True
280  return False
281 
282 
283 # Get The Largest Integer Less Than Or Equal To
284 
285 
286 def less_or_equal(number):
287  try:
288  return math.floor(number)
289  except BaseException:
290  raise RuntimeError('An Error Has Occured: Number Not Provided (0016)')
291 
292 
293 # Compare 2 Values
294 
295 
296 def compare(value1, value2, comparison):
297  if not isinstance(comparison, str):
298  raise WrongInput("ERROR: comparison argument must be a string")
299  if comparison not in ['is', 'or', 'and']:
300  raise WrongInput(
301  "ERROR: comparison argument must be 'is', 'or' or 'and'")
302  if comparison == 'is':
303  return operator.is_(value1, value2)
304  elif comparison == 'or':
305  return operator.or_(value1, value2)
306  elif comparison == 'and':
307  return operator.and_(value1, value2)
308 
309 
310 # Find all the factors of a number
311 
312 
313 def factors(number):
314  """
315 
316  Find all of the factors of a number and return it as a list
317 
318  number:
319  The number to find the factors for
320 
321  """
322 
323  factors = []
324  for i in range(1, number + 1):
325  if number % i == 0:
326  factors.append(i)
327  return factors
328 
329 
330 def eulercalc(faces, edges, verticies):
331  """
332 
333  Calculate the value of Euler's formula of a shape
334 
335  faces:
336  The faces of the shape
337 
338  edges:
339  The edges of the shape
340 
341  verticies:
342  The verticies of the shape
343 
344  """
345 
346  return verticies + edges - faces
347 
348 
349 def randomnum(minimum=1, maximum=2):
350  """
351 
352  Generate a random number
353 
354  minimum:
355  The minimum number to generate. Default is 1.
356 
357  maximum:
358  The maximum number to generate. Default is 10.
359 
360  """
361 
362  if isnum(minimum):
363  if isnum(maximum):
364  return random.randint(minimum, maximum)
365  else:
366  raise RuntimeError('Invalid Value (0016)')
367  else:
368  raise RuntimeError('Invalid Value (0016)')
369 
370 
371 def isfib(number):
372  """
373 
374  Check if a number is in the Fibonacci sequence
375 
376  number:
377  Number to check
378 
379  """
380 
381  num1 = 1
382  num2 = 1
383  while True:
384  if num2 < number:
385  tempnum = num2
386  num2 += num1
387  num1 = tempnum
388  elif num2 == number:
389  return True
390  else:
391  return False
392 
393 
394 def isprime(number):
395  """
396 
397  Check if a number is a prime number
398 
399  number:
400  The number to check
401 
402  """
403 
404  if number == 1:
405  return False
406  for i in range(2, int(number**0.5) + 1):
407  if number % i == 0:
408  return False
409  return True
410 
411 
412 def convertbase(number, base=10):
413  """
414 
415  Convert a number in base 10 to another base
416 
417  number:
418  The number to convert
419 
420  base:
421  The base to convert to. Default is 10.
422 
423  """
424 
425  integer = number
426  if not integer:
427  return '0'
428  sign = 1 if integer > 0 else -1
429  alphanum = string.digits + string.ascii_lowercase
430  nums = alphanum[:base]
431  res = ''
432  integer *= sign
433  while integer:
434  integer, mod = divmod(integer, base)
435  res += nums[mod]
436  return ('' if sign == 1 else '-') + res[::-1]
437 
438 
439 def isnum(value):
440  """
441 
442  Check if a value is a type of number (decimal or integer)
443 
444  value:
445  The value to check
446 
447  """
448 
449  try:
450  return bool(isinstance(value, (float, int)))
451  except BaseException:
452  return False
453 
454 
455 def quadrant(xcoord, ycoord):
456  """
457 
458  Find the quadrant a pair of coordinates are located in
459 
460  xcoord:
461  The x coordinate to find the quadrant for
462 
463  ycoord:
464  The y coordinate to find the quadrant for
465 
466  """
467 
468  xneg = bool(xcoord < 0)
469  yneg = bool(ycoord < 0)
470  if xneg is True:
471  if yneg is False:
472  return 2
473  return 3
474  elif xneg is False:
475  if yneg is False:
476  return 1
477  return 4
478 
479 
480 def flipcoords(xcoord, ycoord, axis):
481  """
482 
483  Flip the coordinates over a specific axis, to a different quadrant
484 
485  xcoord:
486  The x coordinate to flip
487 
488  ycoord:
489  The y coordinate to flip
490 
491  axis:
492  The axis to flip across. Could be 'x' or 'y'
493 
494  """
495 
496  axis = axis.lower()
497  if axis == 'y':
498  if xcoord > 0:
499  return str(xcoord - xcoord - xcoord) + ', ' + str(ycoord)
500  elif xcoord < 0:
501  return str(xcoord + abs(xcoord) * 2) + ', ' + str(ycoord)
502  elif xcoord == 0:
503  return str(xcoord) + ', ' + str(ycoord)
504  elif axis == 'x':
505  if ycoord > 0:
506  return str(xcoord) + ', ' + str(ycoord - ycoord - ycoord)
507  elif ycoord < 0:
508  return str(ycoord + abs(ycoord) * 2) + ', ' + str(xcoord)
509  elif ycoord == 0:
510  return str(xcoord) + ', ' + str(ycoord)
511 
512 
513 def lcm(num1, num2):
514  """
515 
516  Find the lowest common multiple of 2 numbers
517 
518  num1:
519  The first number to find the lcm for
520 
521  num2:
522  The second number to find the lcm for
523 
524  """
525 
526  if num1 > num2:
527  bigger = num1
528  else:
529  bigger = num2
530  while True:
531  if bigger % num1 == 0 and bigger % num2 == 0:
532  return bigger
533  bigger += 1
534 
535 
536 def hcf(num1, num2):
537  """
538 
539  Find the highest common factor of 2 numbers
540 
541  num1:
542  The first number to find the hcf for
543 
544  num2:
545  The second number to find the hcf for
546 
547  """
548 
549  if num1 > num2:
550  smaller = num2
551  else:
552  smaller = num1
553  for i in range(1, smaller + 1):
554  if ((num1 % i == 0) and (num2 % i == 0)):
555  return i
556 
557 
558 def pythrule(first, second):
559  """
560 
561  Calculate the area of a right angled trangle based on Pythagoras' Theorem
562 
563  first:
564  The length of the first axis (x or y)
565 
566  second:
567  The length of the second axis (x or y)
568 
569  """
570 
571  return (first * second) / 2
def posnegtoggle
Definition: maths.py:258
def numprop
Definition: maths.py:233
def circleconvert
Definition: maths.py:129
def factors
Definition: maths.py:313
def flipcoords
Definition: maths.py:480
def autosolve
Definition: maths.py:13
def isnum
Definition: maths.py:439
def amountdiv
Definition: maths.py:154
def randomnum
Definition: maths.py:349
def autohard
Definition: maths.py:37
def compare
Definition: maths.py:296
def equation
Definition: maths.py:67
def scientific
Definition: maths.py:89
def quadrant
Definition: maths.py:455
def isinfinite
Definition: maths.py:270
def fracsimplify
Definition: maths.py:111
def less_or_equal
Definition: maths.py:286
def eulercalc
Definition: maths.py:330
def isprime
Definition: maths.py:394
def lcm
Definition: maths.py:513
def squareroot
Definition: maths.py:191
def isfalse
Definition: maths.py:277
def power
Definition: maths.py:184
def constant
Definition: maths.py:165
def hcf
Definition: maths.py:536
def factorial
Definition: maths.py:198
def isfib
Definition: maths.py:371
def pythrule
Definition: maths.py:558
def convertbase
Definition: maths.py:412
def average
Definition: maths.py:207