Pythonのabs()
Python abs() 関数は絶対値を返します。数値の絶対値は常に正であり、Python では数値の負の符号が削除されます。
例:
Input: -29 Output: 29
Python abs() 関数の構文
Python の abs() 関数の構文は次のとおりです。
構文: 腹筋(数字)
数値: 整数、浮動小数点数、複素数。
戻る: 絶対値を返します。
Python abs() 関数の例
Python の abs() 関数の例をいくつか見てみましょう。
整数引数を持つ abs() 関数
この例では、整数値を引数として Python の abs() 関数に渡し、その値を出力してその動作を確認します。
Python3
# An integer> var> => -> 94> print> (> 'Absolute value of integer is:'> ,> abs> (var))> |
出力:
Absolute value of integer is: 94
浮動小数点数を使用した abs() 関数
この例では、float データを abs() 関数に渡し、絶対値を返します。
Python3
# floating point number> float_number> => -> 54.26> print> (> 'Absolute value of float is:'> ,> > abs> (float_number))> |
出力:
Absolute value of float is: 54.26
複素数を使用した abs() 関数
この例では、Python の複素数を abs() 関数に渡し、絶対値を返します。
Python3
# A complex number> complex_number> => (> 3> -> 4j> )> print> (> 'Absolute value or Magnitude of complex is:'> ,> abs> (complex_number))> |
出力:
Absolute value or Magnitude of complex is: 5.0
Python abs() 関数を使用した時間-距離の計算
この例では、方程式は、物体の速度、移動距離、所要時間の関係を示しています。私たちは、速度、時間、距離が決してマイナスではないことを知っています。したがって、abs() メソッドを使用して、正確な時間、距離、速度を計算します。
使用される公式:
- 距離 = 速度 * 時間
- 時間 = 距離 / 速度
- 速度 = 距離 / 時間
速度、距離、時間を計算する 3 つの関数を宣言しました。次に、Python abs() 関数を使用して、正と負の整数と浮動小数点の値を渡します。 abs() 関数は、負の値を正の値に自動的に変換し、速度、距離、時間の計算に使用されます。
Python3
# Function to calculate speed> def> cal_speed(dist, time):> > print> (> ' Distance(km) :'> , dist)> > print> (> ' Time(hr) :'> , time)> > return> dist> /> time> # Function to calculate distance traveled> def> cal_dis(speed, time):> > print> (> ' Time(hr) :'> , time)> > print> (> ' Speed(km / hr) :'> , speed)> > return> speed> *> time> # Function to calculate time taken> def> cal_time(dist, speed):> > print> (> ' Distance(km) :'> , dist)> > print> (> ' Speed(km / hr) :'> , speed)> > return> speed> *> dist> # Driver Code> # Calling function cal_speed()> print> (> ' The calculated Speed(km / hr) is :'> ,> > cal_speed(> abs> (> 45.9> ),> abs> (> -> 2> )))> print> ('')> # Calling function cal_dis()> print> (> ' The calculated Distance(km) :'> ,> > cal_dis(> abs> (> -> 62.9> ),> abs> (> 2.5> )))> print> ('')> # Calling function cal_time()> print> (> ' The calculated Time(hr) :'> ,> > cal_time(> abs> (> 48.0> ),> abs> (> 4.5> )))> |
出力:
Distance(km) : 45.9 Time(hr) : 2 The calculated Speed(km / hr) is : 22.95 Time(hr) : 2.5 Speed(km / hr) : 62.9 The calculated Distance(km) : 157.25 Distance(km) : 48.0 Speed(km / hr) : 4.5 The calculated Time(hr) : 216.0