Today is Pi day (3.14), and I wanted to do "something" Pi related with GatewayScript.

GatewayScript "Number" precision is that of JavaScript numbers (15 digits), because they are stored as (IEEE 754) double precision floating point numbers.

So for doing any "precision" computing with GatewayScript arbitrary precision numbers are needed.

Googling around I found "decimal.js" library with easy to use MIT license:

https://github.com/MikeMcl/decimal.js/

I gave that library a try, downloaded the .zip, and uploaded "decimal.js" to "local:" folder of DataPower.

Then I computed Pi by evaluating 1,000,000 loops of non-alternating series forumula from Wikipedia,

and did output difference to 1025 digit precision value of PI:

ðŸ’» time ( coproc2 add.js <('') http://dp3-l3:2227; echo )

"5.0000000002976264338e-7"

real 0m9.558s

user 0m0.003s

sys 0m0.016s

ðŸ’»

This is the GatewayScript script used:

ðŸ’» cat pi.js

var Decimal = require('local:///decimal.js');

var PI = new Decimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789');

var n, pi = new Decimal(0.0), two = new Decimal(2);

for(n=0; n<1000000; ++n) {

var n4 = new Decimal(4*n);

pi = pi.add(two.dividedBy(n4.plus(1).times(n4.plus(3))));

}

pi = pi.times(4);

session.output.write(PI.minus(pi));

ðŸ’»

Extended latency log says "...,AXF=5,AGS=9772,...", and there are 6 "Decimal" operations inside loop, 4 outside, resulting in 1.63μs per Decimal operation on average:

ðŸ’» bc -ql

(9772-5)/(1000000*6+4)*1000

1.62783224811183459000

Yes, slow convergence for the chosen formula (there are much quicker converging formulas).

But good to see how easy arbitrary precision math can be done in GatewayScript based on a library with acceptable license for most.

Hermann.