C庫 - tanh() 函式



C庫函式`tanh()`接受型別為double的引數(x),並返回x的雙曲正切值。

傳遞給tanh()的引數可以是任何實數,無論是正數還是負數。tanh()函式在現實生活中的應用包括:神經網路、訊號處理、統計和資料分析。

語法

以下是C庫函式`tanh()`的語法:

double tanh(double x)

引數

此函式只接受一個引數:

  • x - 這是一個浮點值。

返回值

此函式返回x的雙曲正切值。

示例1

以下是一個C庫程式,演示`tanh()`函式的使用。

#include <stdio.h>
#include <math.h>

int main () {
   double x, ret;
   x = 0.5;

   ret = tanh(x);
   printf("The hyperbolic tangent of %lf is %lf degrees", x, ret);
   
   return(0);
}

輸出

以上程式碼產生以下結果:

The hyperbolic tangent of 0.500000 is 0.462117 degrees

示例2

在這個程式中,角度設定為30度作為輸入。因此,我們可以調整`angle_degrees`的值來探索不同的角度,並觀察它們對應的雙曲正切值。

#include <stdio.h>
#include <math.h>

int main() {
    // angle in degree
    double angle_deg = 30.0; 

    // Convert degrees to radians
    double angle_radians = angle_deg * (M_PI / 180.0);

    // Calculate tanh
    double res = tanh(angle_radians);

    printf("tanh(%.2lf degrees) = %.4lf\n", angle_deg, res);
    return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

tanh(30.00 degrees) = 0.4805

示例3

下面的例子描述了使用tanh()逼近e^x的方法。這裡,我們定義了一個自定義函式`my_exp()`,它使用公式`ex = (1 + tanh(x/2)) / (1 - tanh(x/2))`來返回結果。

#include <stdio.h>
#include <math.h>

double my_exp(double x) {
    return (1.0 + tanh(x / 2.0)) * (1.0 - tanh(x / 2.0));
}

int main() {
    double x = 2.0; 

    double apx_exp = my_exp(x);

    printf("Approximate e^%.2lf = %.6lf\n", x, apx_exp);
    return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Approximate e^2.00 = 0.419974
Approximate e^2.00 = 0.419974
廣告
© . All rights reserved.