コアダンプの数だけ強くなれるよ

見習いエンジニアの備忘log

Linuxのbcコマンドで高校数学

bcは四則演算や三角関数を使った計算をすることができるコマンド。対話モードで電卓のように使用したり、数式を記載したファイルを食わせて計算したりできる。

使いどころが難しいけど覚えると何かと楽しいので軽くおさらいしてみた。

使い方

使用頻度が高いものだけピックアップ。

コマンドオプション

コマンド 意味
bc 対話モードで起動
bc [file] fileに記載した式を実行
bc -l 数学ライブラリを使用

文法

制御文 意味
define function(x) 任意の式を定義
print "[text]" 任意の文字列表示
quit 終了

数学ライブラリ

制御文 意味
s (x) sinx
c (x) cosx
a (x) arctanx (アークタンジェント)

→ a(1) = {\pi}/{4} となるので {\pi}= arctan(1) * {4}のようにして\piを使うことができる。

実行例

階乗

factorial.bc

define factorial(x) {
  if (x <= 1) return (1);
  return (factorial(x-1) * x);
}

factorial(1)
factorial(2)
factorial(3)
factorial(4)
factorial(5)
factorial(6)
factorial(7)
factorial(8)
factorial(9)
factorial(10)
quit
[user@localhost ~]$ bc factorial.bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1
2
6
24
120
720
5040
40320
362880
3628800
三角関数

sin^2x + cos^2x = 1
cos^2x = \frac{1+ cos2x }{2}

この数式通りの値になるか確かめてみる。

trigon.bc

define pi(x) { return x * a(1) * 4 }

define square(x) { return x * x }

print "\n"
print "Trigonometric function\n"
print "\n"
print "sin^2(PI/2) + cos^2(PI/2) = "
square(s(pi(1/2))) + square(c(pi(1/2)))

print "\n"

print "cos^2(PI/4) = "
square(c(pi(1/4)))

print "(1 + cos(2*(PI/4))) / 2 = "
(1 + c(2 * pi(1/4)) )/ 2

print "\n"

quit
[user@localhost ~]$ bc -l trigon.bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

Trigonometric function

sin^2(PI/2) + cos^2(PI/2) = 1.00000000000000000000

cos^2(PI/4) = .50000000000000000001
(1 + cos(2*(PI/4))) / 2 = .50000000000000000001


はてなってTexが使えるんですね、知らなかった...(^-^;)