1

I am learning C and I was asked to compute e^x and compare it with the value given by exp function in math.h and this is what I did:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
   
 double exponential( double x ,  double n,   double  p ){  
double  i=1;
 if(n<0)
 return i;
 else   
 i=i+(x/p)*(exponential(x,n-0.00001,p+1));}


int main(){                  
   double x,n,p;
 scanf("%lf",&x);
 printf("math.h e^x =     %lf\n",exp(x));
 printf("calculated e^x = %lf\n",exponential(x,1,1));
 return 0;}

but I was only getting correct answers up to x = 30 after that its deviating more as I increase x. Can someone tell me how I should change the code for more precision.

user
  • 87
  • 5
  • 2
    Please copy and paste the code properly. Your code has syntax errors and bad formatting. – kiner_shah Feb 23 '22 at 06:26
  • 1
    e to the X is a very difficult function to render precise for large X. Using greater precision types and math is the usual approach. – chux - Reinstate Monica Feb 23 '22 at 06:27
  • 1
    Using `long double` could help. – Gerhard Feb 23 '22 at 06:29
  • 1
    Your function does not return a value in the case of a else. – Gerhard Feb 23 '22 at 06:40
  • @Gerhard when I used long double its returning " nan " as output and I don't know why and regarding return a value in case of else , I want my function to run until I reach n <0 so I think its not required to return a value in case of else . Please correct me if I am wrong – user Feb 23 '22 at 06:50
  • 3
    @user You are wrong. Not returning a value is undefined behaviour. The fact the you sometimes get the correct answer is no proof that your code actually work. – Gerhard Feb 23 '22 at 07:32
  • @user if you do not return `i` remove the line `i=i+(x/p)*(exponential(x,n-0.00001,p+1));` since it has no purpose. – Gerhard Feb 23 '22 at 07:35
  • adding `return i;` after `i=i+(x/p)*(exponential(x,n-0.00001,p+1));` would at least be valid c code and would not influence your current code. – Gerhard Feb 23 '22 at 07:38

1 Answers1

0

Your code has undefined behaviour (compare If a function returns no value, with a valid return type, is it okay to for the compiler to return garbage? ).
That is all the explanation needed for any unwanted or unexpected behaviour.
Compare What is Undefined Behaviour in C? .

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • but when ever I change the code like removing if else and introducing while ( n>0) and returning I , it gives me a segmentation fault and I don't know why and there is no overflow as well – user Feb 23 '22 at 07:27
  • 1
    Then please create a new question on the different problem you have with a program without undefined behaviour. – Yunnosch Feb 23 '22 at 07:29