473,395 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

sqrt function in cmath library

I am writing a program which will use the ceiling and floor of square
roots.

If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?

Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999

You might say "try it". The problem is that I can't try infinitely
many cases. I'm asking about square numbers in general.

I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.

Paul Epstein

Oct 21 '05 #1
10 7289
pa**********@att.net wrote:
I am writing a program which will use the ceiling and floor of square
roots.

If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?

Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999

You might say "try it". The problem is that I can't try infinitely
many cases. I'm asking about square numbers in general.

I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.


You don't need to run infinitely many number variations. 'double' has
more digits than 'unsigned int' to store the mantissa, most likely. If
you take the square root of UINT_MAX+1, you get a value. You only need
to run sqrt(UINT_MAX + 1) tests, which is probably 65536:

int r = -1;
for (int i = 0; i < 65536; i++) {
double d = i; // exact
r = sqrt(d*d);
if (r != i) // bust!
break;
}

// examine 'r' here

V
Oct 21 '05 #2
pa**********@att.net wrote:
I am writing a program which will use the ceiling and floor of square
roots.

If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?

Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999
It just might do that. The problem, though, isn't with the sqrt
function but with the internal representation of decimal numbers. We
actually discussed this just yesterday - searching the archives might
help.
You might say "try it". The problem is that I can't try infinitely
many cases. I'm asking about square numbers in general.
You might try it, but you'd only find out how it works on your system.
I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.


That's probably the most consistent and portable solution.

Kristo

Oct 21 '05 #3
pa**********@att.net wrote:
I am writing a program which will use the ceiling and floor of square
roots.

If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?

Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999

You might say "try it". The problem is that I can't try infinitely
many cases. I'm asking about square numbers in general.

I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.


Well, as far as I can tell the C++ standard just incorporates the semantics
of these functions from the C standard. I checked the draft version that I
have, and I did not find *any* guarantees as to precision. The wording of
the C standard for sqrt is:

The sqrt functions return the value of the square root.

This, clearly is a lie since in general the square root of a double is not
representable by a double. Thus, for all, I know

double sqrt ( double x ) {
return 0.0;
}

is a standard compliant implementation. It is a "quality of implementation"
thing. So, maybe you are better off asking the vendor of your library.

Best

Kai-Uwe Bux
Oct 21 '05 #4
> pa**********@att.net wrote:
I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.

Kristo <kr*******@gmail.com> wrote: That's probably the most consistent and portable solution.


Another way that should be consistent and portable (though it does
introduce some additional overhead, and has ugly casts in it):
double d1 = /* something */;
double d2 = std::sqrt(d1);

int lower = static_cast<int>(std::floor(d2));
int upper = static_cast<int>(std::ceil(d2));

if (lower == upper) {
// sqrt was exact
}
--
Marcus Kwok
Oct 21 '05 #5
Thank you for this code (and thanks to others who tried to help me.)

I could easily have written this program myself. The reason I didn't
test it in this way, is that I had no idea that 65536 trials were
sufficient. Thanks for the interesting suggestion of where such bounds
lie.

As an aside, it might be worth pointing out that my compiler gives a
warning to the above code when sqrt is applied to an integer type. It
runs perfectly but gives a warning.

I'm still not sure I have a 100% grasp of what is on-topic and what
isn't. I just mentioned the word "compiler" which seems to be a severe
criminal offence in this newsgroup.

I am very inexperienced in this area. From my standpoint, the whole
philosophy of "Let's narrow it down to the language. Let's never ever
mention other programming issues such as compilers and platforms." is a
philosophy that makes absolutely no sense whatsoever to me. I assume
that it makes no sense _to me_ because I'm so inexperienced, and that a
veteran of newsgroups and computing would find such a narrow definition
very sensible.

Paul Epstein

Victor Bazarov wrote:
pa**********@att.net wrote:
I am writing a program which will use the ceiling and floor of square
roots.

If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?

Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999

You might say "try it". The problem is that I can't try infinitely
many cases. I'm asking about square numbers in general.

I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.


You don't need to run infinitely many number variations. 'double' has
more digits than 'unsigned int' to store the mantissa, most likely. If
you take the square root of UINT_MAX+1, you get a value. You only need
to run sqrt(UINT_MAX + 1) tests, which is probably 65536:

int r = -1;
for (int i = 0; i < 65536; i++) {
double d = i; // exact
r = sqrt(d*d);
if (r != i) // bust!
break;
}

// examine 'r' here

V


Oct 21 '05 #6
<top posting rearranged - if you put your reply after the message to
which you are replying everyone can follow the discussion more easily>
pa**********@att.net wrote:
Victor Bazarov wrote:
pa**********@att.net wrote:

<snip>
I'm still not sure I have a 100% grasp of what is on-topic and what
isn't. I just mentioned the word "compiler" which seems to be a severe
criminal offence in this newsgroup.
http://www.parashift.com/c++-faq-lit...t.html#faq-5.9

The rest of the FAQ is well worth reading too.
I am very inexperienced in this area. From my standpoint, the whole
philosophy of "Let's narrow it down to the language. Let's never ever
mention other programming issues such as compilers and platforms." is a
philosophy that makes absolutely no sense whatsoever to me. I assume
that it makes no sense _to me_ because I'm so inexperienced, and that a
veteran of newsgroups and computing would find such a narrow definition
very sensible.


It's very sensible *in the context of this newsgroup*. When you ask a
question, you want as many people to read it as possible. That way, you
are more likely to get the right answer, and, very importantly, if
someone gives you the wrong answer, you are more likely to see someone
else correct it.

Now, imagine you are a C++ language expert who is prepared to give some
time to helping other people with C++ language questions. If you have
to sift through compiler and platform specific questions all the time
to find the occasional language question, you are likely to soon get
bored and give up reading and contributing.

In no way does any of that suggest that it is unacceptable to have
questions about your compiler or platform. Of course you will have
questions. But, in the same way that restricted topicality raises the
quality of C++ language help available here, restricted topicality in a
compiler-specific newsgroup (see the FAQ link I posted) has the same
effect there.

You will get high quality, peer-reviewed answers from the right experts
by posting to the right group. Don't be surprised to sometimes see the
same people helping you in more than one newsgroup either.

Gavin Deane

Oct 21 '05 #7
Thanks a lot.

I don't understand static_cast<int> -- I could probably google this
though, if you don't have the time to give extra details.

By the way, I _do_ understand the basic class notation, std::floor etc.
(using the standard namespace from the maths library -- floor is a
function from that class etc.)

[To receive help, I find it's sometimes a good practice to say what I
do understand (hopefully), as well as what I don't understand.]
Paul Epstein
Marcus Kwok wrote:
pa**********@att.net wrote:
I can easily write a program using an epsilon variable that will round
numbers to integers only if they are within epsilon of an integer.
However, this may be unnecessary -- it may already be built into the
sqrt function.


Kristo <kr*******@gmail.com> wrote:
That's probably the most consistent and portable solution.


Another way that should be consistent and portable (though it does
introduce some additional overhead, and has ugly casts in it):
double d1 = /* something */;
double d2 = std::sqrt(d1);

int lower = static_cast<int>(std::floor(d2));
int upper = static_cast<int>(std::ceil(d2));

if (lower == upper) {
// sqrt was exact
}
--
Marcus Kwok


Oct 22 '05 #8
> Marcus Kwok wrote:
double d1 = /* something */;
double d2 = std::sqrt(d1);

int lower = static_cast<int>(std::floor(d2));
int upper = static_cast<int>(std::ceil(d2));

if (lower == upper) {
// sqrt was exact
}

pa**********@att.net wrote: I don't understand static_cast<int> -- I could probably google this
though, if you don't have the time to give extra details.
std::floor() and std::ceil() both return doubles. the static_cast<int>
tells it to convert the value from a double to an int, so you can store
it in an int variable exactly (assuming the value won't overflow).
[To receive help, I find it's sometimes a good practice to say what I
do understand (hopefully), as well as what I don't understand.]


Yes, also, you should not top-post.

--
Marcus Kwok
Oct 22 '05 #9

de*********@hotmail.com wrote:
<top posting rearranged - if you put your reply after the message to
which you are replying everyone can follow the discussion more easily>
pa**********@att.net wrote:
Victor Bazarov wrote:
pa**********@att.net wrote:


<snip>
I'm still not sure I have a 100% grasp of what is on-topic and what
isn't. I just mentioned the word "compiler" which seems to be a severe
criminal offence in this newsgroup.


http://www.parashift.com/c++-faq-lit...t.html#faq-5.9

The rest of the FAQ is well worth reading too.
I am very inexperienced in this area. From my standpoint, the whole
philosophy of "Let's narrow it down to the language. Let's never ever
mention other programming issues such as compilers and platforms." is a
philosophy that makes absolutely no sense whatsoever to me. I assume
that it makes no sense _to me_ because I'm so inexperienced, and that a
veteran of newsgroups and computing would find such a narrow definition
very sensible.


It's very sensible *in the context of this newsgroup*. When you ask a
question, you want as many people to read it as possible. That way, you
are more likely to get the right answer, and, very importantly, if
someone gives you the wrong answer, you are more likely to see someone
else correct it.

Now, imagine you are a C++ language expert who is prepared to give some
time to helping other people with C++ language questions. If you have
to sift through compiler and platform specific questions all the time
to find the occasional language question, you are likely to soon get
bored and give up reading and contributing.

In no way does any of that suggest that it is unacceptable to have
questions about your compiler or platform. Of course you will have
questions. But, in the same way that restricted topicality raises the
quality of C++ language help available here, restricted topicality in a
compiler-specific newsgroup (see the FAQ link I posted) has the same
effect there.

You will get high quality, peer-reviewed answers from the right experts
by posting to the right group. Don't be surprised to sometimes see the
same people helping you in more than one newsgroup either.

Gavin Deane


Gavin,

I like this reply, which is encouraging, respectful and helpful.

However, I nevertheless remain completely unconvinced of your argument
that it is healthy for this newsgroup to avoid discussion of compilers
and platforms

Surely, decisions about c++ code are influenced by judgments about how
the code will be treated on various platforms or compilers. (Accepting
that portability is a vital issue, I assume programmers consider all
commonly used platforms and compilers.)

However, how can there be discussion of these coding/language issues if
people are fined $5000 by the newsgroup police whenever they say
something like " I wrote .... and my dev c++ compiler said ... What
does ... compiler message mean?" ? The draconian enforcement of these
heavy financial penalties is preventing valuable discussion on pure
language issues concerning c++ programming. The c++ coding works
together with the platforms and the compilers in a symbiotic fashion.

I know a famous writer, Marcus Dontbe Gullible, who submitted what he
thought was a great idea to his publisher. He wanted to write a book
about high-school teaching which scrupulously avoided any mention of
high-school students. Unsurprisingly, the publisher laughed at
Marcus's idea, and thought it ridiculous. The raison d'etre of this
newsgroup -- discussing c++ without discussing compilers or platforms
-- seems analogous to Marcus's unworkable concept.

I also find it absurdly ironic that, in marked contrast to the attitude
towards compiler/platform discussions, the following posting, which was
_wildly irrelevant_, induced a long and sober thread of replies, and
did not seem to be condemned as OT by anybody.

Yesterday's irrelevant (but apparently not judged OT) thread began as
follows:

" I would like to share my distress at the way I have been treated in
my new entry-level job as a java programmer. (I have 3 months
programming experience). My salary is less than 2 million dollars a
year, and my boss has never offered to provide me with a chauffeur to
drive me into work, even though I live in a neighboring town.
Furthermore, last week he treated me to dinner at a Chinese restaurant,
and I was shocked and appalled to notice a small stain on one of the
tablecloths.

Are such experiences typical of everyone, or am I just unlucky?"

Nevertheless, despite all I've said, I enjoy this newsgroup so far and
my questions have been very well answered -- it has been a happy
discovery.

Paul Epstein

Oct 22 '05 #10
pa**********@att.net wrote:
[...]
However, I nevertheless remain completely unconvinced of your argument
that it is healthy for this newsgroup to avoid discussion of compilers
and platforms
[...]


While discussing cutting instruments in a cutting instruments newsgroup,
one should be careful not to veer away and begin asking how to cut hair
with those instruments or how to plow garden soil. It is undoubtedly
topical to discuss suitability of some materials for making cutting
instruments, but techniques of holding those instruments while operating
on a tumor or chopping salad belong to surgical and cooking newsgroups,
respectively.
Oct 22 '05 #11

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

Similar topics

6
by: Prune Tracy | last post by:
Hi, I can't get this seemingly harmless code to compile with Comeau online. #include <cmath> typedef float (*float_func)(float); typedef double (*double_func)(double); int main() {...
7
by: Aric | last post by:
Hi, I'm a bit new to programming in general, really I've just picked it up as a hobby, and so I've started by reading "Practical C Programming" by Steve Oualline. Things have been going fine in...
2
by: Maor Mishkin | last post by:
I've changed from double to decimal calculations but I can't find a math library for decimal (mainly for sqrt), Thanks Maor
13
by: Michael McNeil Forbes | last post by:
I would like to write a module that provides some mathematical functions on top of those defined in math, cmath etc. but I would like to make it work with "any" type that overloads the math...
12
by: Thomas Zhu | last post by:
hello all, n is an 32bit-integer, how to calculate sqrt(n) I know high(n) is the the value, but how to use bit operation to implement this function. thanks in advance. yours Yin
16
by: daniell | last post by:
I created a function: void round(double & num) In the same class file I have also included the cmath header filer When I try to compile I get an ambiguity error. If I recall correctly, doesn't...
5
by: Bernhard Reinhardt | last post by:
Hi, is there a "standard"-library like cmath that contains a signum function? Searching the web I only found "make your own implementation!". If I make my own subroutine, I have to decide...
30
by: copx | last post by:
I am writing a program which uses sqrt() a lot. A historically very slow function but I read on CPUs with SSE support this is actually fast. Problem: C's sqrt() (unlike C++ sqrt()) is defined to...
13
by: mohi | last post by:
hello everyone, i use a function called minor to find the minor of an element of a matrix , i declare it as : float minor(float A,int m,int n,int i,int j);//find the minor in A and define...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.