-2

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

  • So you want to solve for `s`, given `s'` and `f`? Just do the algebra. – ddejohn Jul 03 '22 at 04:08
  • 1
    This is not an LCM problem. This is an algebra problem. The answer is `1 / (1/f - 1/s')`. In your example, s=`2`. – Tim Roberts Jul 03 '22 at 04:19
  • The very [definition of LCM](https://en.wikipedia.org/wiki/Least_common_multiple) describes it in terms of integers, so it's unclear what you expect. – Mark Ransom Jul 03 '22 at 16:04

1 Answers1

0

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.