Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth root of a number

I wrote a program to calculate nth root of a number upto 2 decimal places. eg 4th root of 81 is 3., 3rd root of 125 is 5.Its working nicely except for the 2nd root of 4. It's giving the output 1.99 instead of 2. Here is the code.

#include<stdio.h>
int main(int argc, char **argv)
{
    double root1(int,int);
    int n;
    int num1;
    double root;
    printf("\n\n-----------This is the programme to find the nth root of a number-----------\n\n");
    printf("Enter a nuber greater then 1 : ");
    scanf("%d",&num1);
    if(num1>1)
    {
        printf("Enter the value for 'n'(the root to be calculated) : ");
        scanf("%d",&n);
        root = root1(num1,n);
        printf("%d th Root of %d is %f\n\n", n,num1,root);
    }
    else
        printf("wrong entry");
    return 0;
}

double root1(int a, int b)
{
    int j;
    double i,k;
    double incre = 0.01;
    for(i=1; i<=a; i = i+incre)
    {
        for(j=0;j<b;j++)
        {
            k=k*i;
        }
        if(a<k)
        {
            return(i-incre);
            break;
        }
        else
            k=1;
    }
}

I have tried it for hours, but can't rectify it. can anybody debug this?? I will be very thankful.

like image 376
narayanpatra Avatar asked Aug 16 '10 15:08

narayanpatra


2 Answers

You need to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

Floating point numbers—which are what is normally used to represent non-integers—are inherently limited. Those limits allow good performance but at the cost of such anomalies.

like image 155
Richard Avatar answered Oct 26 '22 12:10

Richard


That's because computers can't handle real numbers properly.

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

like image 35
Federico klez Culloca Avatar answered Oct 26 '22 11:10

Federico klez Culloca