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
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.
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.
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.
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.
If your calculations are sensitive to this kind of difference then you will need other measures (a redesign).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With