How do I make LCM works with floating numbers?

1.1k Views Asked by At

Newbie to python...

Currently I'm writing a code for physics calculator, mirror especially, the formula of the mirror is 1/s + 1/s' = 1/f.

Example, I want to input the number to the s' is 3 and the f is 1.2

1/s + 1/3 = 1/1.2

...and now I wanted the LCM between them to be known but since LCM in python can't work with float numbers, only integer. So, how do I make math.lcm works with float numbers?

I use python 3.9.13

1

There are 1 best solutions below

0
Matías Santurio On

Not sure why you need to calculate the LCM but something like this would work:

import math

def lcm_float(a, b, precision):
    a = round(a, precision)
    b = round(b, precision)
    return math.lcm(int(a*10**precision), int(b*10**precision))/10**precision

It's basically converting the floats to integers, calculating the LCM, and going back to floats. The precision is how many decimal places you will be considering.