Skip to content

Instantly share code, notes, and snippets.

@misode
Created June 7, 2019 20:34
Show Gist options
  • Save misode/47e15abaa234943d942e64d57749c85a to your computer and use it in GitHub Desktop.
Save misode/47e15abaa234943d942e64d57749c85a to your computer and use it in GitHub Desktop.

Calculating the sqrt of a number

This method for calculating the square root uses an iterative algorithm known as the Babylonian method.

You need to run some commands once (or on every /reload).

scoreboard objectives add const dummy
scoreboard players set 2 const 2

scoreboard objectives add sqrt dummy

This is the sqrt function that you would call. You put the input number into input sqrt and you get the sqrt of it in result sqrt.

scoreboard players set counter sqrt 0
scoreboard players operation result sqrt = input sqrt
scoreboard players operation result sqrt /= 2 const
function sqrt_loop

This is the sqrt_loop function. The 16 defines how precise the result will be.

scoreboard players add counter sqrt 1
scoreboard players operation temp sqrt = input sqrt
scoreboard players operation temp sqrt /= result sqrt
scoreboard players operation temp sqrt += result sqrt
scoreboard players operation temp sqrt /= 2 const
scoreboard players operation result sqrt = temp sqrt
execute if score counter sqrt matches ..16 run function sqrt_loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment