No, it returns -1 for any integer greater than zero which is not a perfect square, returns the square root of any positive perfect square, and doesn't have a return statement at all for n < 1.
If I'm reading this right, you're essentially making a guess, and taking the average between your new guess and your previous guess. This makes the new guess slightly closer each time. Is that right?
it's not simply an average. you linearly approximate the function using the differential (basically taking the tangent curve to the function at the point x=your guess) (which is a good approximation iff the function has certain properties and your first guess has certain properties). Then you find the root of this linear function and use that root as the approximation for the next step.
Wikipedia has a good article about that, I hope that my description is interesting enough to make you curious enough to read it.
Wait wait... is that actually what the code from u/greenismyhomeboy is doing?
I took a look at Newton's method and it's actually pretty intuitive and cool! But it just really doesn't look like that's what this code is doing. If it is, it's doing it in a very clever and counter-intuitive way, like the iterative Fibonacci method. That one really threw me for a loop.
I admit I don't have enough willpower right now (I'm stoned) to actually check if his code is the Newton method. it might not be that, might be some other kind of approximation,maybe his code is wrong or maybe his code is equivalent by reworking the math. maybe I can look at it again tomorrow...
I just explained the Newton method because you mentioned it in the comment and his code at first glance looked like it might be doing that.
Anyway, I suggest you trying to implement Newton's method in something like Excel or code or whatever to really understand it: it's one of the most used algorithm to find roots for arbitrary functions, so it's very useful!
No, I think that one's called Heron's method (I just had it in a class last week). It doesn't converge as fast as Newton or the secant method (iirc), but get's the job done.
Scrap that. Herons method is a special case of Newton's method (since the differential of the sqrt function is known).
It is being method, but the truck is that you need to transform a sqrt function into a function of which you need to find the zeroes. Only then can you apply newton's method.
I would never directly compare doubles like that. I guarantee there are some values for which that results in in infinite loop. For this algorithm, I think you want:
Wouldn't this go on and on until it finally reached the max of type double and cut of the decimal so it finally finishes. That means 1.8 ×10308 loop runs.(googled it sry may be wrong). Or was I wrong interpreting this?
it goes for however long it takes for sqrt and temp to match 15 decimal digits of precision. using the above algorithm a random 12 digit number takes ~24 loops. I set n = DBL_MAX and it spit out a root after 517 loops
Cast the float as an int while preserving it's bitwise configuration, then it does a Newton approximation via bitwise operations to save time over doing it on the floats itself.
This is a very nice and clever one but it still is slower than this implementation in assembly:
Also, according to that same article, this method has the same level of precision as the sqrt() function in the standard libraries where the C bit-level hacking function has a precision of (only) 97%.
Most likely now all the compilers convert sqrt(n) to some kind of similar expression.
sin/cos are easy for a LUT because you have a finite domain. For a sqrt() function which can take any possible value you'd need a lot of RAM for that LUT, unless you know for a fact that the domain is going to be limited to a specific range that isn't too big to be manageable.
You can expand square root x around x=1 using taylor expansion and take the first few terms. By doing this you don't even need loops. You just need to hard code the expansion lol
I think that wouldn't work for x >> 1 because the Taylor series can't approximate the function everywhere in the domain. if it could, then sqrt(x) would be a polynomial, which it isn't. The Newton method will work for every x and will give a sufficiently good approximation with less than 8 iterations if you choose the first approximant well enough.
The problem here is not the loop, it's the assumption that all roots are integers, so the code only finds roots of natural squares like 1,4,9,25,… You cannot brute-force loop over real numbers, since they are not countable.
Edit: I see the function should return an int, so maybe this is the intended behaviour.
Math libs are going to call the built-in floating point sqrt() method of your CPU. For x86 that would be something like SQRTSD, it looks like ARM uses VSQRT. Newton's method would only be used for low power embedded devices which may not have floating point hardware at all.
What’s the time complexity for using a hardware-level instruction for sqrt? Does it use more clock cycles than other floating point ops (add/multiply/etc) or is it about the same?
I'll be honest, I'm not 100% sure about this one. Looking at some instruction latency tables I found (see https://agner.org/optimize/), for a Haswell generation CPU, which is what I have, scalar floating point operations are 3 cycles for ADDSD and SUBSD, 5 cycles for MULSD, 10-20 cycles for DIVSD, and 16 for SQRTSD. So yes, it's using more cycles, but way, way, way less than you could possibly do by Newton's method.
It's worth noting that, as I understand, the CPU is actually looking for the result to converge, which depends on how close it is to a LUT entry, etc etc. I believe that the instruction can actually exit early if you're computing the square root of a particularly fortunate number. It's almost certainly doing an iterative method, possibly even just Newton's method, but hardware operations are nearly always faster than software.
Compilers don't know ahead of time the hardware that the code is going to run on. Your CPU when you compile something isn't necessarily going to be the same as someone else's when they try to run your software.
Yes, there are hardware CPU implementations of sqrt() on a lot of CPUs now but when C was still young there really wasn't.
What? Yes, a compiler most definitely knows what hardware you're going to run your program on. If I compile a program with an x86 compiler it's not gonna magically run on ARM. There is the concept of CPU generation and additional features in newer ones, but the basic instructions I referenced above are from MMX introduced in the Pentium 1 era, and to my knowledge nothing commercially targets anything that old. The oldest target for 32-bit I've seen recently is Pentium 2, and most consumer and enterprise hardware is 64-bit meaning it's at least an AMD K8 or newer (roughly similar to the Pentium 4 in era). All of these have extensive and non-optional support for floating point math in hardware, include sqrt().
There is also the concept of having multiple binaries based on detected architecture, which some math libraries like Intel MKL use to ensure that the fastest code is used regardless of CPU generation. It's not as common due to binary size, but worth it for the performance increase of using something like AVX over SSE. The "worst case" is still going to target something with, at a minimum, hardware floating point support.
That's not really bad code? I mean, the code itself is pretty awful, no doubt, but your friend is clearly a beginner here. We should not be mocking this person's attempts to learn.
On the other hand, WHAT THE HELL IS UP WITH THAT WHITE SPACE?
Some times I press enter like 15 times to give me space to look at what i'm actually doing without any extra visual noise, I did it more when I was learning and I do it less and less now a days.
Of course I'd then just clean it up after I was done thinking, but maybe that's what happened here?
Honestly, only issues here to me (for a beginner) is white space and layout for readability.
Hot take, (for most cases) braces should be on a new line, and at most only 3 empty new lines between statements, if for any thing just segmenting your code into sections (but if you need to do that you should probably just refactor anyway
Ok, how about a 'break' immediately following a 'return'? Obviously, that 'break' statement is never going to be reached. A compiler would probably flag this as "unreachable code".
Neither the 'else if' nor the 'else' statements should even be there. The 'else if' statement simply confirms that the previous 'if' statement failed, and repeats the conditions in the 'for' statement in order to avoid falling through to the 'else' statement. The code wrapped by the 'else' statement would only be executed after the last pass through the loop failed to find a square root. That code, the 'return -1', should have just been placed outside the loop.
It's a brute force algorithm, which should be avoided unless there is no other way, but it's a poorly written brute force algorithm.
Using some really easy math knowledge, you can check only to values of n/2. And your program works twice as fast for every number which don't have natural square root.
It works tho, the final else{} will be reached only when i=n. I agree that the return -1; should be outside the for loop and the else if{} should be just else{} to make it a bit more efficient. To further optimize, you need to adjust the n, as going past n/2 doesn't make sense: (n/2+1)*(n/2+1) will always be greater than sqrt(n)*sqrt(n). Further optimization will brings us to Newton's formula, I believe.
Haha. It caught my eye too but what bugged me the most is the extra blank lines after the break leading up to the first elseif. Also the break after the return i that prevents it from ever doing anything at all.
25
u/Encursed1 Nov 19 '21
So it returns -1 for everything except 1 is my understanding. Also why is there a break after a return?
139
u/Thenderick Nov 19 '21
Just curious, how do you calculate the square root without math libs? I can also only imagine a brute force for loop.
204
u/xiipaoc Nov 19 '21
That's not really bad code? I mean, the code itself is pretty awful, no doubt, but your friend is clearly a beginner here. We should not be mocking this person's attempts to learn.
On the other hand, WHAT THE HELL IS UP WITH THAT WHITE SPACE?
15
u/Jimmy_Slim Nov 19 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
14
u/vapocalypse52 Nov 19 '21
What's wrong is a picture of the screen.
5
u/[deleted] Nov 19 '21
Couldn't you just do
int square_root(int n) { return n**0.5;}?2
u/randomnoob20 Nov 19 '21
you can fix that easily by changing i <= n to i <= n*n /s
3
u/possiblyis Nov 19 '21
That’s not
too bad.
2
u/[deleted] Nov 19 '21
Love it hahahha. Everything is so wrong
1
u/deftware Nov 20 '21
It's genius.
1
u/[deleted] Nov 19 '21
The parentheses around
i*ipisses me off for some reason more than anything...-1
u/incoralium Nov 19 '21
A = A**0.5
-10
u/Yangishrobin Nov 19 '21
Red flag #1: no math libs were allowed