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

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

when I used the code below, I got the wrong value for the root of the cube ( 1 printed for n = 64 ).

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

Now that I have changed the code a bit,

 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 (when debugging), but this method printed 4 (this is correct).

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

+6
source share
5 answers

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

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

A similar problem with multiplication, but usually less trap, integral operands give an integral result, which risks overflow. This otherwise reflects the way the processor works, it has clear instructions for these operations, IMUL vs. FMUL and IDIV vs. FDIV. The latter is known as a bug in the Pentium processor :)

+13
source

You can try running this code to work with the root of the cube.

 textBox2.Text = Math.Pow(Convert.ToDouble(textBox1.Text), 0.3333333333333333).ToString(); 
+1
source

The error (which, incidentally, is only 4E-16 - 400 quint-million) is caused by floating-point errors.

You can get around this by rounding the number if it is at a specific threshold:

 public static void cubicPairs(double n) { double root = (System.Math.Pow(n, (1/3))); double roundedRoot = Math.Round(root); if (Math.Abs(roundedRoot - root) < VERY_SMALL_NUMBER) return roundedRoot; else return root; } 

Where VERY_SMALL_NUMBER could be, say, 1e-10 .

0
source
 public static void Main() { int a= int.Parse(Console.ReadLine()); int sum=0; for(int i=0 ; i<= a ;i++) { for(int j=0 ; j<i ;j++) { sum =+ (i*i); } Console.WriteLine("Number is : {0} and cube of the {0} is :{1} \n",i,sum*i); } } 
0
source

Try

 Math.Ceiling(Math.Pow(n, (double)1 / 3)); 
0
source

Source: https://habr.com/ru/post/1202149/


All Articles