How to get the value of Pi in bc calculations

  • Post author:
  • Post last modified:November 13, 2024
  • Reading time:2 mins read

1.0 π

While using bc for calculations, the value of π is sometimes required. Sure, you might remember it as 3.1416, but it is better to use a higher precision value. And it's quite simple to do that.

First, we need to start bc with the option -l (ell) to use the standard math library. With the usage of the math library, the following functions become available to us.

  • s (x), for the sine of x, where x is in radians,
  • c (x), for the cosine of x, where x is in radians,
  • a (x), for the arctangent of x, the returned arctangent is in radians,
  • l (x), for the natural logarithm of x,
  • e (x), for the exponential function of raising e to the power of x, and
  • j (n, x), for the Bessel function of integer order n of x.

Since the arctangent of 1 is π/4 radians, the expression 4*a(1) gives the value of π and can be used in any expression. For example, if we wish to find the radius of a circle having an area of 263 square units, we can do the following.

$ bc -l
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'. 
sqrt (263 / (4 * a (1)))
9.14961748196813671663

Lastly, we can print the value of π in a shell script by passing the expression 4*a(1) as standard input to bc.

$ echo "4*a(1)" | bc -l
3.14159265358979323844

Karunesh Johri

Software developer, working with C and Linux.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments