# [Batch File] Pi Calculator.



## Gavlar (Jun 8, 2009)

Just threw together this batch file out of curiosity to calculate Pi:


```
set /a pi=4
set /a denom=3
set /a osc=-1
set /a count=0
:loop
cls
set /a count+=1
set /a osc=-1^%count%
if %osc% equ -1 (set /a pi=%pi%-(4/%denom%)) if %osc% equ 1 (set /a pi=%pi%+(4/%denom%))
set /a denom+=2
echo %pi%
pause
goto loop
```
Uses some basic mathematical processes but doesnt seem to work, the batch file merely closes instantaneously. Im not really much a programmer at all, could someone tell me where Ive gone wrong?

Thanks,
Gavin.


----------



## Squashman (Apr 4, 2003)

Probably not as easy as you think. Did you perhpas google search before you started this.
http://thedailywtf.com/Articles/Stupid-Coding-Tricks-A-Batch-of-Pi.aspx


----------



## Gavlar (Jun 8, 2009)

Thanks for your reply.
No, I did not search before starting. I was procrastinating and the idea hit me so I thought I'd through it together.

It uses the Leibniz formula for Pi. :
1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 .... = Pi/4
Therefore: 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 = Pi

I think where the Batch file is crashing is the oscillation function (-1^n). This is to change the operator between + or -
This fixes that (and makes the script alot simpler):

```
set /a pi=4
set /a denom=3
set /a count=0
:loop
set /a pi=%pi%-4/%denom%
set /a denom+=2
echo %pi%
pause
set /a pi=%pi%+4/%denom%
set /a denom+=2
echo %pi%
pause
goto loop
```
Now, however, I realise that batch only supports integer numeric values. This complicates everything. In order to use decimals, it would require alot more experience on my part.

Looks like I'm giving up on that.

Thanks anyway, 
Gavin.


----------



## TheOutcaste (Aug 8, 2007)

Also batch doesn't support exponentiation. The *^* is the symbol for the Bitwise Exclusive OR operation. And since it's also the batch escape character, you'd have to quote the line, or double the character (also the *%* symbols aren't needed with *Set /A*):
*set /a osc=-1^^count
set /a osc="-1^count"*

This gives the same result as *Set /a osc-=1* if you start with *osc=-1*

You also have the two If statements on the same line without an &, though in this case you want them on separate lines, or use an If Else construct:

```
if %osc% equ -1 (set /a pi=pi-(4/denom)) Else (set /a pi=pi+(4/denom))
```


----------

