Datapack Utils

Datapack Utils

2k Downloads

There is no sqrt math function

misode opened this issue · 7 comments

commented

This is a basic math function, yet it is not included in this datapack.

commented

It's actually extremely easy.

function sqrt

scoreboard players set counter temp 0
scoreboard players operation return temp = input temp
scoreboard players operation return temp /= #2 temp
function sqrt_loop

function sqrt_loop

scoreboard players add counter temp 1
scoreboard players operation temp temp = input temp
scoreboard players operation temp temp /= return temp
scoreboard players operation temp temp += return temp
scoreboard players operation temp temp /= #2 temp
scoreboard players operation return temp = temp temp
execute if score counter temp matches ..16 run function sqrt_loop
commented

Wow didnt expect that. But it can be tweaked to need less computing time if you add a new var that stores the last result. If this is the same as the result from this run you'll can stop the sqrt_loop.

commented

This could be done with Newtons Method or by the digit-by-digit calculation but these are hard to implement.

commented

But it can be tweaked to need less computing time if you add a new var that stores the last result

@Ultrahero How would you increase performance here? Other than unrolling the loop I don't see any optimizations you could make.

commented

Hm, I've been trying to put together a sqrt root function (haven't put too much time into it though). Looks like I at least found the right equation.
I can include that in the next update.

commented

@misode
I'll show it with an example.
If the input is 25:
return =25
return =25/2=12
1st run:
temp =25
temp =25/12=2
temp = 2+12=14
temp = 14/2=7=return
2nd run:
temp=25
temp=25/7=3
temp=3+7= 10
temp=10/2=5=return
3rd run:
temp =25
temp= 25/5=5
temp= 5+5=10
temp= 10/2=5

Now for every loop it will still be 5. If you would say at the end of a loop that the last result will be saved to compare it later. E.g.
1)execute if score compare temp matches return temp run scoreboard players set counter temp 17
2)scoreboard player operation compare temp = return temp

And if you would add this at the end of the loop function it will increase performance at least for small inputs

commented

Ah, like that. Doesn't really matter I think. Scoreboard operations are pretty fast anyways.