473,804 Members | 3,182 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

is it ok to cast variables? simple function using std::pow

Hi everyone,

I wrote a very simple function to try to understand the casting of
variables in C++. The function is

function foo()
{
std::vector<int test(100);
randomize(test) ;
unsigned long x = 0;
for(int i=0; i<test.size(); i++)
x += (unsigned long)(allele(i) *std::pow((doub le)k,
(double)i));
}

The function randomize just creates random values inside the vector.
This was the only way I made it to work without having any warnings
from the compiler. Since the std::pow takes two doubles as parameters,
I needed to cast the integer values into doubles. Also, I needed to
cast those double results into an unsigned long integer. I don't
really like using casting (I have a bad feeling every time I use it)
but I couldn't find a better way to do this. Does anyone have a better
way to do it? Is there anything wrong with casting variables into
different types?

Thank you all.

Jun 7 '07 #1
5 2543
On 7 Jun., 03:58, aaragon <alejandro.ara. ..@gmail.comwro te:
Hi everyone,

I wrote a very simple function to try to understand the casting of
variables in C++. The function is

function foo()
{
std::vector<int test(100);
randomize(test) ;
unsigned long x = 0;
for(int i=0; i<test.size(); i++)
x += (unsigned long)(allele(i) *std::pow((doub le)k,
(double)i));
}

The function randomize just creates random values inside the vector.
This was the only way I made it to work without having any warnings
from the compiler. Since the std::pow takes two doubles as parameters,
I needed to cast the integer values into doubles. Also, I needed to
cast those double results into an unsigned long integer. I don't
really like using casting (I have a bad feeling every time I use it)
but I couldn't find a better way to do this. Does anyone have a better
way to do it? Is there anything wrong with casting variables into
different types?

Thank you all.
It is difficult to give a definite reply when I can't see your code
(allele is undefined), but if the problem is a warning when converting
from double to unsigned long, I'd put in a static_cast. The casts to
double are not needed.
I would never allow a C-style cast to creep into my code, so get rid
of those.

/Peter

Jun 7 '07 #2
"aaragon" <al************ **@gmail.comwro te in message
news:11******** **************@ q69g2000hsb.goo glegroups.com.. .
Hi everyone,

I wrote a very simple function to try to understand the casting of
variables in C++. The function is

function foo()
{
std::vector<int test(100);
randomize(test) ;
unsigned long x = 0;
for(int i=0; i<test.size(); i++)
x += (unsigned long)(allele(i) *std::pow((doub le)k,
(double)i));
}

The function randomize just creates random values inside the vector.
This was the only way I made it to work without having any warnings
from the compiler. Since the std::pow takes two doubles as parameters,
I needed to cast the integer values into doubles. Also, I needed to
cast those double results into an unsigned long integer. I don't
really like using casting (I have a bad feeling every time I use it)
but I couldn't find a better way to do this. Does anyone have a better
way to do it? Is there anything wrong with casting variables into
different types?
Bascially, that's how I also use pow with intergers, although I use
static_cast rather than a c-style cast as it's explicit what I'm doing. (
static_cast<dou ble>k, static_cast<dou ble>i )

I put a static_cast in when I get a warning and I know that what I'm doing
is what I want to do and I either won't be getting over/underflow or I'm
handling it myself somewhere.
Jun 7 '07 #3
On Jun 7, 3:58 am, aaragon <alejandro.ara. ..@gmail.comwro te:
I wrote a very simple function to try to understand the casting of
variables in C++. The function is
function foo()
{
std::vector<int test(100);
randomize(test) ;
unsigned long x = 0;
for(int i=0; i<test.size(); i++)
x += (unsigned long)(allele(i) *std::pow((doub le)k,
(double)i));
}
The function randomize just creates random values inside the vector.
This was the only way I made it to work without having any warnings
from the compiler. Since the std::pow takes two doubles as parameters,
I needed to cast the integer values into doubles.
Nonsense. Int's convert implicitly to double, and it's a
non-lossy conversion, so there's not even the slightest excuse
for a warning.
Also, I needed to
cast those double results into an unsigned long integer.
That's also an implicit conversion, although since it is a lossy
one, a warning is somewhat understandable. I would use a cast
here, if only to tell the reader that I meant it.
I don't
really like using casting (I have a bad feeling every time I use it)
but I couldn't find a better way to do this. Does anyone have a better
way to do it? Is there anything wrong with casting variables into
different types?
Well, there's certainly nothing wrong with converting a value to
a different type, when that's what you want. Sometimes, it's
even necessary:
std::cout << instanceCount / totalCount * 100 << " percent" ;
won't give the desired results unless you convert at least one
of instanceCount or totalCount to a floating point type. And
surely you've written things like:
f( std::string( a ) + ".txt" ) ;
, casting a C style string to an std::string.

These are conversion casts, involving values, and there's
generally nothing wrong with them. If the conversion is "lossy"
(the target type can't hold all of the information present in
the orginal type), then some care should be exercised,
particularly in cases like converting to an integral value from a
floating point (where there are several different rounding rules
you might want to apply), but otherwise, I see no problem with
them.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 7 '07 #4
James Kanze wrote:
On Jun 7, 3:58 am, aaragon <alejandro.ara. ..@gmail.comwro te:
>I wrote a very simple function to try to understand the casting of
variables in C++. The function is
>function foo()
{
std::vector<int test(100);
randomize(test) ;
unsigned long x = 0;
for(int i=0; i<test.size(); i++)
x += (unsigned long)(allele(i) *std::pow((doub le)k,
(double)i));
}
>The function randomize just creates random values inside the vector.
This was the only way I made it to work without having any warnings
from the compiler. Since the std::pow takes two doubles as parameters,
I needed to cast the integer values into doubles.

Nonsense. Int's convert implicitly to double, and it's a
non-lossy conversion, so there's not even the slightest excuse
for a warning.
Just curious, is it guaranteed to be non-lossy? I'd have thought it
depends on the size of int whether all value of int are exactly
representable as a double.

--
Ian Collins.
Jun 7 '07 #5

Ian Collins wrote in message...
James Kanze wrote:
[snip]
Nonsense. Int's convert implicitly to double, and it's a
non-lossy conversion, so there's not even the slightest excuse
for a warning.
Just curious, is it guaranteed to be non-lossy? I'd have thought it
depends on the size of int whether all value of int are exactly
representable as a double.
[ being in a 'scatter-brained' mood and only haveing a single-brain-cell,
I'd read the following with great caution! <G]

Since the standard only qualifies an 'int' type to 16 bits, I'd say "yes"
(IMHO).
If a system increases an 'int' to 32 bits (one bit being the sign bit), and
does not increase the double's bits, I'd NOT buy that system!!
[ I think you are thinking about the fractional part of the double (which
will be zero(s) for an int conversion). See below (IntMax).]

Test your own system:

#include <limits// and <iostream>
{
using std::cout // for NG post
cout<<" dbl max() ="
<< std::numeric_li mits<double>::m ax()<<std::endl ;
cout<<" int max() ="<< std::numeric_li mits<int>::max( )<<std::endl;
cout <<" dbl digits ="
<<(std::numeric _limits<double> ::digits)<<std: :endl;
cout <<" int digits ="
<<(std::numeric _limits<int>::d igits)<<std::en dl;
double IntMax( std::numeric_li mits<int>::max( ) );
cout <<" double IntMax ="<<IntMax<<std ::endl;

// assumes your system has type 'long long' ( like GNU GCC).
cout<<" LL max() ="
<< std::numeric_li mits<long long>::max()<<s td::endl;
cout <<" LL digits ="
<<(std::numeric _limits<long long>::digits)< <std::endl;
double LLMax( std::numeric_li mits<long long>::max());
cout <<" double LLMax ="<<LLMax<<std: :endl;
}
/* - output (win98se, P4) -
dbl max() =1.79769e+308
int max() =2147483647
dbl digits =53
int digits =31
double IntMax =2147483647.000 000
LL max() =92233720368547 75807
LL digits =63
double LLMax =92233720368547 75800.000000
*/
Note the loss in 'LLMax'. (trying to stuff 63bits into 53bits)

If you are not sure, use a 'long double'! <G>
cout<<" LD digits ="
<<(std::numeric _limits<long double>::digits )<<std::endl;
// LD digits =64

Or, were you asking if the C++ standards committee "guarantees it"?

[ Ok, the laugh is NOT affecting me, blah! <GMind yer manners or i'll
attach something! <G]
--
Bob R
POVrookie
Jun 8 '07 #6

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

Similar topics

2
2470
by: cupiemayo | last post by:
Hello. I'm trying to make a sort of generic integral class, holding the boundary values and the integrand. Eventually I'd like to use it inside a class, like the example below. I think the problem is that in order to pass a member function, I have to qualify the name a bit differently, for example: typedef double (astro::universe::*pfn)(double); (by the way, I don't think this actually worked...) But doing this sort of thing of...
10
1793
by: rg | last post by:
Hi all, I was wondering if anyone had dealt with a similar problem. I need to use a template function as the parameter for a particular function (also template function). The program compiles into an object file but then at the final stage it says that it can't find template function. The platform is WindowsXP Pro, MSCV++ ..Net. More specifically what I want to do is write an atl algorithm that will also
15
11658
by: Steven T. Hatton | last post by:
Did I mess something along the way, or is there no function in Standard C++ to raise an (unsigned) int to a power of (unsigned) int returning (unsigned) int? I never gave this a second thought until today. I tried to do it, and discovered <cmath> std::pow() only takes floating point types for the first argument. Sure I could write one. I could have written at least 3 fundamentally differnet versions in the time it took to discover there...
11
4457
by: Russ | last post by:
I have a couple of questions for the number crunchers out there: Does "pow(x,2)" simply square x, or does it first compute logarithms (as would be necessary if the exponent were not an integer)? Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some other (perhaps less efficient) algorithm based on logarithms? Thanks, Russ
8
59580
by: Chris Stankevitz | last post by:
Q1: Does c++ provide pow(int,int)? Q2: If not, why not? Thanks, Chris
4
7383
by: chrisstankevitz | last post by:
Any on consensus on which of these is faster? inline float Square1(float f) { return std::pow(f, 2.0f); } inline float Square2(float f) { return f*f; } Chris
18
2240
by: Peng Yu | last post by:
Hi, I'm wondering if there is any general guideline on when to using something like std::pow(x, n) rather than x * x * x * ... * x (n x's). Thanks, Peng
3
2061
by: Peng Yu | last post by:
Hi, The output of the following program is (-27.7128,16) (-9.09495e-12,32768) Obviously, y*y*y is not equal to x, even the magnitude is off. I'm wondering what is wrong here. Thanks, Peng
2
3144
by: Peng Yu | last post by:
Hi, I have the following program which computes roots of a cubic function. The solution is sensitive to the type, which is due to the truncation error. 'long double T' gives three solutions, and 'typedef double T' gives one solutions. The correct number of solutions should be two, 1 and 2. I know there is some trick to reduce the chance of under or overflow. For example, std::abs(z) shall be implemented as
0
9708
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
9587
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
10588
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
10340
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...
0
9161
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...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3827
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.