Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math "pow" in Java and C# return slightly different results?

I am porting program from C# to java. I've faced a fact that

Java

Math.pow(0.392156862745098,1./3.) = 0.7319587495200227

C#

Math.Pow( 0.392156862745098, 1.0 / 3.0) =0.73195874952002271

this last digit leads to sufficient differences in further calculations. Is there any way to emulate c#'s pow?

Thanx

like image 899
Stepan Yakovenko Avatar asked Apr 12 '12 20:04

Stepan Yakovenko


People also ask

Can we use math POW in C?

Basically in C exponent value is calculated using the pow() function. pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function.

What is a POW in C?

C pow() The pow() function computes the power of a number. The pow() function takes two arguments (base value and power value) and, returns the power raised to the base number. For example, [Mathematics] xy = pow(x, y) [In programming] The pow() function is defined in math.

What can I use instead of math POW in Java?

Calculating the Power of a Number in Java Without Using Math pow() Method. In Java, we can calculate the power of any number by : Calculating the power of a number through while loop or for loop. Calculating the power of a number by the divide and conquer method.


2 Answers

Just to confirm what Chris Shain wrote, I get the same binary values:

// Java
public class Test
{
    public static void main(String[] args)
    {
        double input = 0.392156862745098;
        double pow = Math.pow(input, 1.0/3.0);            
        System.out.println(Double.doubleToLongBits(pow));
    }
}

// C#
using System;

public class Test
{
    static void Main()
    {
        double input = 0.392156862745098;
        double pow = Math.Pow(input, 1.0/3.0);            
        Console.WriteLine(BitConverter.DoubleToInt64Bits(pow));
    }
}

Output of both: 4604768117848454313

In other words, the double values are exactly the same bit pattern, and any differences you're seeing (assuming you'd get the same results) are due to formatting rather than a difference in value. By the way, the exact value of that double is

0.73195874952002271118800535987247712910175323486328125

Now it's worth noting that distinctly weird things can happen in floating point arithmetic, particularly when optimizations allow 80-bit arithmetic in some situations but not others, etc.

As Henk says, if a difference in the last bit or two causes you problems, then your design is broken.

like image 194
Jon Skeet Avatar answered Sep 18 '22 11:09

Jon Skeet


If your calculations are sensitive to this kind of difference then you will need other measures (a redesign).

like image 39
Henk Holterman Avatar answered Sep 21 '22 11:09

Henk Holterman