如何在Python中获得双重精度值等于Java Float.valueof()

发布于 2025-01-22 07:28:39 字数 430 浏览 2 评论 0原文

我正在尝试将Java计算迁移到Python,在那里我看到浮点值计算结果的差异

:例如:在Java

public class Main
{
    public static void main(String[] args) {
        long lg_val =  Long.parseLong("16191753860");
        float fg_val = Float.valueOf(lg_val);
        System.out.println(fg_val);
    }
}

结果-1.61917542E10(打印双重值),

但在Python Float()中,在Python float()方法中返回相同的值16191753860.0

如何 返回。在Python中获取双重精确计算以获得相同的结果

I am trying to migrate a java calculation to python, where I see the difference in the float value calculation results

for example: in Java

public class Main
{
    public static void main(String[] args) {
        long lg_val =  Long.parseLong("16191753860");
        float fg_val = Float.valueOf(lg_val);
        System.out.println(fg_val);
    }
}

result - 1.61917542E10 (prints the double value)

but in python float() method returns same value 16191753860.0

How to get the double-precision calculation in python to get the same results

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

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

发布评论

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

评论(2

伴我心暖 2025-01-29 07:28:39

Python float是双精度浮点号。实际上,您的Java示例使用了单个Precision float,这就是为什么它以科学符号格式化(因为它已经超过了整数精度)。

如果您想打印出python中浮子的科学符号,无论它是否越过精确边界,请使用e格式。

f'{lg_val:e}' - > '1.619175E+10'


或使用Java中的双精度号,请使用

double fg_val = Double.valueOf(lg_val);

The python float is a double precision floating point number. It is in fact your Java example that is using the single precision float, which is why it formats in scientific notation (as it has gone above integer precision).

If you want to print out the scientific notation of a float in python regardless of if it's crossed over the precision boundary, use the e format.

f'{lg_val:e}' -> '1.619175e+10'


Or to use a double precision number in Java instead, use

double fg_val = Double.valueOf(lg_val);
眉目亦如画i 2025-01-29 07:28:39

您可以使用numpy.float64()。在您的示例中,

import numpy as np 

np.float64(lg_val)

You can use numpy.float64(). In your example,

import numpy as np 

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