Skip to main content
36 of 39
deleted 51 characters in body
Οurous
  • 8.1k
  • 1
  • 16
  • 38

Cobra

class Trig
    const mod as float = 0.0174532925199433f
    var time as System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch()
    var file as String[] = File.readAllLines('trig.in')
    var input as float[] = float[](1)
    var sin_out as float[] = float[](1)
    var cos_out as float[] = float[](1)
    var tan_out as float[] = float[](1)
    def main
        .compute(0)
        .time.reset
        .input = float[](.file.length)
        .sin_out = float[](.file.length)
        .cos_out = float[](.file.length)
        .tan_out = float[](.file.length)
        for num, line in .file.numbered, .input[num] = float.parse(line)
        .time.start
        for num in .input.length, .compute(num)
        .time.stop
        for num in .file.length, .file[num] = (.sin_out[num].toString('0.000000E+0') + ' ' + .cos_out[num].toString('0.000000E+0') + ' ' + .tan_out[num].toString('0.000000E+0'))
        File.writeAllLines('trig.out', .file)
        print .time.elapsed
    def compute(index as int)
        degrees as float = .input[index]
        #add `degrees %= 360` for numbers greater than 360
        sin as float = .sin(degrees)
        if degrees % 180 <> 90, cos as float = (1 - (sin * sin)).sqrt * ((degrees - 180).abs - 90).sign
        else, cos as float = 0
        .tan_out[index] = Math.round((sin / cos) * 10000000) / 10000000
        .sin_out[index] = Math.round(sin * 10000000) / 10000000
        .cos_out[index] = Math.round(cos * 10000000) / 10000000
    def sin(degrees as float) as float
        rad as float = sin as float = degrees * .mod
        two as float = rad * rad
        sin -= (rad *= two) / 6
        sin += (rad *= two) / 120
        sin -= (rad *= two) / 5040
        sin += (rad *= two) / 362880
        sin -= (rad *= two) / 39916800
        sin += (rad *= two) / 6227020800
        sin -= (rad *= two) / 1307674368000
        sin += (rad *= two) / 355687428096000
        sin -= (rad *= two) / 121645100408832000
        sin += (rad *= two) / 51090942171709440000f
        sin -= (rad *= two) / 25852016738884976640000f
        sin += (rad *= two) / 15511210043330985984000000f
        sin -= (rad *= two) / 10888869450418352160768000000f
        sin += (rad *= two) / 8841761993739701954543616000000f
        return sin

Compile it with cobra filename -turbo

Tests: AMD FX6300 @5.1GHz

  • The 360 * 10000 test used by the C answer runs in 500ms (vs 190ms)

  • The 4-entry test used by the Python and Java answers runs in 0.41µs (vs 30µs, 3µs)

  • The 1000 random angle test used by the Fortran answer runs at 100ns per angle (vs 10µs)

Οurous
  • 8.1k
  • 1
  • 16
  • 38