Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Cube root of a number Using System.Math.Pow() method in C#

Tags:

c#

pow

While writing a program I came across finding the cube root of a number in one of my functions.

when I used the below code, I was getting an incorrect value for the cube root (1 was getting printed for n = 64).

public static void cubicPairs(double n)
{
    double root = (System.Math.Pow(n, (1/3)));
    Console.WriteLine(root);
}

Now after I changed the code slightly to this,

public static void cubicPairs(double n)
{
    double root = (System.Math.Pow(n, (1.0/3.0))); //Changed how second parameter is passed
    Console.WriteLine(root);
}

I got root = 3.9999999999999996 (while debugging) but the method was printing 4 (which is correct).

Why is there a difference between the two values and if this has to do with the second parameter to the System.Math.Pow() method (i.e, 1.0/3.0 which is a recursive value), what should I use to find cube root so that I get 4 (while debugging) rather than 3.9999999999999996?

like image 402
gkb Avatar asked Sep 09 '14 11:09

gkb


2 Answers

This is a standard trap in the { curly brace languages }, C# included, a division with integral operands is performed as an integer division, not a floating point division. It always yields an integer result, 1 / 3 produces 0. Raising any number to the power of 0 produces 1.0

You force a floating point division by converting one of the operands to double. Like 1.0 / 3 or (double)integerVariable / 3.

Similar problem with multiplication, but usually less of a trap, integral operands produce an integral result that risks overflow. This otherwise reflects the way the processor works, it has distinct instructions for these operations, IMUL vs FMUL and IDIV vs FDIV. The latter one being rather famous for a bug in the Pentium processor :)

like image 117
Hans Passant Avatar answered Nov 14 '22 03:11

Hans Passant


You can try running this code for cube root functionality.

textBox2.Text = Math.Pow(Convert.ToDouble(textBox1.Text), 0.3333333333333333).ToString();
like image 34
Nitin Gaur Avatar answered Nov 14 '22 03:11

Nitin Gaur