Initial commit: Pi calculation benchmark with 34 languages
- Added implementations for: bash, brainfuck, c, cpp, crystal, csharp, d, dart, elixir, erlang, fortran, go, haskell, java, javascript, julia, kotlin, objective-c, scala, typescript, lua, nim, odin, perl, php, python, r, ruby, rust, swift, zig, assembly, vimscript, wolfram - All implementations use Machin's formula: π/4 = 4*arctan(1/5) - arctan(1/239) - Build system with ./build.sh, test system with ./test.sh - Performance testing with ./run_all.sh - Comprehensive README.md explaining performance differences - Test framework verifies correctness against known π values
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import java.math.BigInteger
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
// Calculate arctan(1/x) using Taylor series
|
||||
// arctan(1/x) = 1/x - 1/(3*x^3) + 1/(5*x^5) - ...
|
||||
fun arctan(x: Int, decimals: Int): BigInteger {
|
||||
val scale = BigInteger.TEN.pow(decimals + 10)
|
||||
val xBig = BigInteger.valueOf(x.toLong())
|
||||
val xSquared = xBig * xBig
|
||||
|
||||
var term = scale / xBig
|
||||
var result = BigInteger.ZERO
|
||||
var n = 0
|
||||
|
||||
while (term != BigInteger.ZERO && n < decimals * 3) {
|
||||
val divisor = BigInteger.valueOf(2L * n + 1)
|
||||
val contrib = term / divisor
|
||||
|
||||
if (n % 2 == 0) {
|
||||
result += contrib
|
||||
} else {
|
||||
result -= contrib
|
||||
}
|
||||
|
||||
term = term / xSquared
|
||||
n++
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
fun calculatePi(decimals: Int): BigInteger {
|
||||
val atan1_5 = arctan(5, decimals)
|
||||
val atan1_239 = arctan(239, decimals)
|
||||
|
||||
// pi = 16*arctan(1/5) - 4*arctan(1/239)
|
||||
return atan1_5 * BigInteger.valueOf(16) - atan1_239 * BigInteger.valueOf(4)
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
var decimals = 100
|
||||
|
||||
if (args.isNotEmpty()) {
|
||||
try {
|
||||
decimals = args[0].toInt()
|
||||
if (decimals < 1) decimals = 100
|
||||
} catch (e: NumberFormatException) {
|
||||
decimals = 100
|
||||
}
|
||||
}
|
||||
|
||||
val pi = calculatePi(decimals)
|
||||
val piStr = pi.toString()
|
||||
|
||||
// Print with decimal point
|
||||
print("3.")
|
||||
val startIndex = 1
|
||||
val endIndex = minOf(startIndex + decimals, piStr.length)
|
||||
print(piStr.substring(startIndex, endIndex))
|
||||
|
||||
// Pad with zeros if needed
|
||||
for (i in 0 until decimals - (endIndex - startIndex)) {
|
||||
print("0")
|
||||
}
|
||||
println()
|
||||
}
|
||||
Reference in New Issue
Block a user