Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to use power operator, like x^y? 2

Status
Not open for further replies.

RajVerma

Programmer
Jun 11, 2003
62
DE
hi all,

I have a strange observation when I was using the symbol ^ thinking that it is like power. but I'm getting the following results that I cudn't understand.

[expr 2^1] = 3
[expr 2^2] = 0
[expr 2^3] = 1
[expr 2^4] = 6
[expr 2^5] = 7
[expr 2^6] = 4
[expr 2^7] = 5
[expr 2^8] = 10
[expr 2^9] = 11
[expr 2^10] = 8
[expr 2^11] = 9

and so on. So my question is what exavtly does this ^ operator do? and how to use power operator?

thanx a lot,
Raj.
 
says:
^ Bit-wise exclusive OR. Valid for integer operands only.

So:

2^1: 00000010 exclusive OR 00000001 = 00000011 = 3
2^2: 00000010 exclusive OR 00000010 = 00000000 = 0
2^3: 00000010 exclusive OR 00000011 = 00000001 = 1


I found the proc power at
proc power {base p} {
set result 1
while {$p>0} {
set result [expr $result*$base]
set p [expr $p-1]
}
return $result
}

Regards,
Dan
 
There's a much easier way. For over 10 years (since Tcl 7.0), expressions have supported the pow() function. pow() accepts 2 floating-point arguments, like [tt]pow($x,$y)[/tt], which would raise x to the y power:

[tt]% set x 2
2
% expr { pow($x, 2) }
4.0
% expr { pow($x, 10) }
1024.0
% expr { pow($x, 5.75) }
53.8173705762[/tt]

As a side note, it's recommended practice -- for performance and other reasons -- to enclose the arguments to expr inside of curly braces {}. See the Tcl'ers Wiki page "expr," for more information and other helpful tips on Tcl expressions. Also check out the expr command reference, for a complete list of supported functions and operations.

- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top