我如何使LCM与浮动数一起使用?

发布于 2025-02-12 08:25:34 字数 366 浏览 1 评论 0原文

Newbie到Python ...

目前,我正在编写一个用于物理计算器的代码,尤其是镜像,镜像的公式为 1/s + 1/s'= 1/f 。

例如,我想将数字输入 s'为3,而 f 为1.2

1/s + 1/3 = 1/1.2

...现在我想知道它们之间的 lcm ,但由于python中的 lcm 无法与float一起使用数字,只有整数。那么,如何使Math.lcm与浮点数一起使用?

我使用python 3.9.13

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很糊涂小朋友 2025-02-19 08:25:34

不确定为什么您需要计算LCM,但是类似的东西会起作用:

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

它基本上是将浮子转换为整数,计算LCM并回到浮子。
精确度是您要考虑的小数位数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文