473,625 Members | 2,717 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking square root algorithm for portability/correctness

Hello:

I posted a thread on comp.programmin g awhile back asking about an algorithm
I implemented on square root. The idea was to use the square root of a
prime number as a convenient way to get a pseudorandom number generator.
So, rather than calculate the square root to try to get a particular
precision answer, you would calculate it to x number of bits. This
particular function takes a radicand and the number of iterations as
arguments. So, for 32-bit unsigned integers, you'd want to iterate 16
times. But for the purposes of pseudorandom generation, the number of
iterations could be arbitrary.

I think I've identified one issue with this technique. Some
experimentatoin seems to indicate it is possible to overflow the difference
operand, which probably makes this algorithm non-sensical after a certain
number of iterations.

The notes for compiling are below. If you have time to take a look, that
would be great.

Thanks,

-Clint

Notes:

Compiling:

% cc -o sqrt -Wall -pedantic -g sqrt.c

If you don't want to see the debug messages, use -DNDEBUG as well.

About the code:

The code is written so it doesn't make any assumptions about the width of
an unsigned long. It estimates this by taking the width of character and
then multiplying by the sizeof the parameterized type: sqrt_t. I made no
attempt to calculate the value bits of an unsigned long. In real life we'd
use the value bits to denote the proper number of iterations to make. The
odd initialization of shift was to account for some oddball machine that
had an odd number of bits in an unsigned long.

I took the algorithm from "Algorithms for Extracting Square Roots and Cube
Roots", Peng, 1981.

Running:

% sqrt 9 16

Usually you want to perform 16 iterations to produce a correct result for a
machine with 32-bit unsigned longs. However, for the purposes of
generating psuedo-random sequences on primes, I was interested in the
behavior if you specified something more arbitrary, like:

% sqrt 2 40

I'd appreciate any comments about correctness and efficiency if you have
any.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef unsigned long sqrt_t;

int main(int argc, char *argv[])
{
sqrt_t a; /* target of sqrt */
sqrt_t root = 0; /* root */
sqrt_t diff; /* running difference */
sqrt_t a_i, b_i;
unsigned width = CHAR_BIT * sizeof(sqrt_t);
int shift = width & 1 ? width - 1 : width - 2;
int i;

if (argc == 3) {
a = strtoul(argv[1], NULL, 10);
i = strtoul(argv[2], NULL, 10);

/* pass 1 */
a_i = a >> shift & 3;

diff = a_i - 1;

if (diff < a_i) /* overflow check */
root = 1;

for (shift -= 2, --i; i > 0; i--, shift -= 2) {

if (shift >= 0) {
a_i = a >> shift & 3;
} else {
a_i = 0;
}

b_i = diff << 2 | a_i;

if (root & 1)
diff = b_i - (root << 2 | 1);
else
diff = b_i + (root << 2 | 3);

root <<= 1;

if (diff < b_i)
root |= 1;

#ifndef NDEBUG
printf("root: %lu, d: %lu, shift: %d\n", root, diff, shift);
#endif
}
printf("%lu\n", root);
} else {
fprintf(stderr, "usage: %s <target> <iterations>\n" , argv[0]);
}

return EXIT_SUCCESS;
}
Nov 14 '05 #1
2 3136
Clint Olsen wrote:
I posted a thread on comp.programmin g awhile back asking about
an algorithm I implemented on square root. The idea was to use
the square root of a prime number as a convenient way to get a
pseudorandom number generator.
...
The code is written so it doesn't make any assumptions about
the width of an unsigned long.
But it does assume that there are no padding bits.
It estimates this by taking the width of character and then
multiplying by the sizeof the parameterized type: sqrt_t.
I made no attempt to calculate the value bits of an unsigned
long.
Why not? It's trivial...

int value_bits = 0;
untype_t x;
for (x = -1, x = x/2+1; x; x >>= 1) value_bits++;
In real life we'd use the value bits to denote the proper
number of iterations to make.
Or, as in the sample I gave in comp.programmin g you can simply
mask the highest eventh bit and shift the mask as you go.
...
Usually you want to perform 16 iterations to produce a
correct result for a machine with 32-bit unsigned longs.
However, for the purposes of generating psuedo-random
sequences on primes, I was interested in the behavior
if you specified something more arbitrary,
Although, that's not something clc delves into.
I'd appreciate any comments about correctness and
efficiency if you have any.
Assuming you have M value bits, your algorithm performs
M-2 + M-4 + M-6 ... shifts. You could reduce this to
precisely M.

My only other style comment is...
sqrt_t root = 0; /* root */
sqrt_t diff; /* running difference */
sqrt_t a_i, b_i;
...
/* pass 1 */
a_i = a >> shift & 3;
diff = a_i - 1;

if (diff < a_i) /* overflow check */
root = 1;


This last if-statement is an obfuscated way of writing...

root = (a_i != 0);

In other words, your 'overflow' occurs if and only if a_i is 0.

--
Peter

Nov 14 '05 #2
On 2005-03-22, Peter Nilsson <ai***@acay.com .au> wrote:
But it does assume that there are no padding bits.
Yes.
Why not? It's trivial...

int value_bits = 0;
untype_t x;
for (x = -1, x = x/2+1; x; x >>= 1) value_bits++;
Yeah, I know it's trivial. I just didn't do it :)
Or, as in the sample I gave in comp.programmin g you can simply
mask the highest eventh bit and shift the mask as you go.
I'll have to look for your post on this.
Assuming you have M value bits, your algorithm performs
M-2 + M-4 + M-6 ... shifts. You could reduce this to
precisely M.


I'm curious how you'd get around this? You need to extract 2 bits from the
radicand (a) for each iteration, and since you have to start with the most
significant bits, you can't just keep a running register and shift off the
bits to the right.
if (diff < a_i) /* overflow check */
root = 1;


This last if-statement is an obfuscated way of writing...

root = (a_i != 0);

In other words, your 'overflow' occurs if and only if a_i is 0.


Thanks for your comments.

-Clint
Nov 14 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8878
by: Jack Smith | last post by:
Hello, any help appreciated with following problem. I figured out the algorithm (I think), just having trouble proving it is optimal. Suppose we are given n tasks each of which takes 1 unit time to complete. Suppose further that each task has a deadline by which it is expected to finish. IF a task is not finished by the deadline, a standard penalty of $10 is applied. The problem is to find a schedule of the tasks that minimizes the...
2
746
by: cplusplus | last post by:
Hello, I have newbie question. I'm stuck on this current assignment. Write a program that prompts the user for two integer values, passes the values to a function where they are multiplied together and the square root of the product is returned and displayed for the user. The function should return a double. Hint: If you multiply an integer by 1.0 the result will be a double. For example:
32
5093
by: someone else | last post by:
hi all I'm a newbie to this group. my apologies if I break any rules. I've wrote a simple program to find the first 1,000,000 primes, and to find all primes within any range (up to 200 * 10^12) it's pretty efficient, it took 15 minutes to compute the first 1,000,000 primes.
25
352
by: Stephen Mayes | last post by:
From lurking on this most excellent newsgroup, I have garnered that an expressed benefit of having a standard is portability of code. I see a lot of open source endeavors that inspire my awe, but I can't see how the authors get paid, so they don't much inspire my ambition for pursuing perfection, which is inate nonetheless. In real life, how many of you knowledgable people are ever actually consigned to write code that will port to very...
32
4979
by: priyam.trivedi | last post by:
Hi! Could anyone tell me how to find the square root of a number without using the sqrt function. I did it by using Newton's Formula. How can it be done by using the Binomial Theorem/Taylor Series? Is there any other way of doing it rather than using series? Thank you, Priyam
4
8465
by: sathyashrayan | last post by:
(This is not a home work question) Dear group, I want a program to find one number between a set of natural number.A program to guess a number in between a Natural number set.This should be a simple task but my mind suddenly got stuck. I am trying to implement a square root function as a practice. I am able to code for the perfect square
10
13626
by: socondc22 | last post by:
my program is trying to use the babylonian algorithm in order to find the square root... i have a number for the number to have the square root taken of and also a number to run the loop... Whenever i go to print out the answer its rounding instead of giving me the answer i need... any help?? double num1, num2, the_root; cout<< "Enter number to have square root taken of it\n"; cin>> num1; cout<< "Enter number for how...
4
8084
by: krishnai888 | last post by:
I had already asked this question long back but no one has replied to me..I hope someone replies to me because its very important for me as I am doing my internship. I am currently writing a code involving lot of matrices. At one point I need to calculate the square root of a matrix e.g. A which contains non-zero off-diagonal elements. I searched for a lot of info on net but no algorithm worked. My best bet for finding square root was to find...
21
11364
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite some time and still not able to get the solution out. so i hope you guys can help me out. of course i am not expecting a full solution, but i would greatly appreciate it if anyone can suggest to me what should i do. i am very new to this subject so...
0
8253
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8635
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6116
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4192
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.