指数函数的值可以使用泰勒级数计算。
= 1 + x / 1! + / 2! + / 3! + ……
为了使用递归来找到它的值,我们将使用静态变量。对于x的幂,我们将使用p,对于阶乘,我们将使用f作为静态变量。
如下所示的函数用于增加x的幂。
p = p*x
下面的函数用于查找阶乘。
f = f*n
下面的函数用于计算序列的总和。
r+p/f
其中r是对函数的递归调用。
以下是上述想法的实现。
C++
// C++ implementation of the approach
#include
// Recursive Function with static
// variables p and f
double e(int x, int n)
{
static double p = 1, f = 1;
double r;
// Termination condition
if (n == 0)
return 1;
// Recursive call
r = e(x, n - 1);
// Update the power of x
p = p * x;
// Factorial
f = f * n;
return (r + p / f);
}
// Driver code
int main()
{
int x = 4, n = 15;
printf("%lf \n", e(x, n));
return 0;
}
Java
// Java implementation of the approach
import java.text.*;
class GFG
{
// Recursive Function with static
// variables p and f
static double p = 1, f = 1;
static double e(int x, int n)
{
double r;
// Termination condition
if (n == 0)
return 1;
// Recursive call
r = e(x, n - 1);
// Update the power of x
p = p * x;
// Factorial
f = f * n;
return (r + p / f);
}
// Driver code
public static void main (String[] args)
{
int x = 4, n = 15;
DecimalFormat df = new DecimalFormat("0.######");
System.out.println(df.format(e(x, n)));
}
}
// This code is contributed by mits
Python3
# Python implementation of the approach
# Recursive Function
# global variables p and f
p = 1.0
f = 1.0
def e(x, n) :
global p, f
# Termination condition
if (n == 0) :
return 1
# Recursive call
r = e(x, n - 1)
# Update the power of x
p = p * x
# Factorial
f = f * n
return (r + p / f)
# Driver code
x = 4
n = 15
print(e(x, n))
# This contributed by ihritik
C#
// C# implementation of the approach
using System;
class GFG
{
// Recursive Function with static
// variables p and f
static double p = 1, f = 1;
static double e(int x, int n)
{
double r;
// Termination condition
if (n == 0)
return 1;
// Recursive call
r = e(x, n - 1);
// Update the power of x
p = p * x;
// Factorial
f = f * n;
return (r + p / f);
}
// Driver code
static void Main()
{
int x = 4, n = 15;
Console.WriteLine(Math.Round(e(x, n),6));
}
}
// This code is contributed by mits
输出:
54.597883