Normalizing a vector

Questions and problems about using polymake go here.
Darksun

Normalizing a vector

Postby Darksun » 12 Nov 2011, 11:44

Hello, I have been trying to make my own algorithm for normalizing a vector (length 1). The problem is that when I take a "new Vector<Rational>," do the computation, and put it into the square root, the square root doesn't know what to do with it because it's Rational.

Here's what I've been trying:

declare $v=new Vector<Rational>([1,7,8,9,6,4,7,6,5]);

declare @array=$v;
print "@array\n";

declare @array2=(1);
declare $sum=0;
for (declare $i=0;$i<9;$i++) {
$sum=$sum+$array[$i]*$array[$i];
}

print sqrt($sum);

sherrmann
Developer
Posts: 27
Joined: 26 Dec 2010, 15:46

Re: Normalizing a vector

Postby sherrmann » 13 Nov 2011, 18:56

There is not much you can do about that. As you noted, the sqrt function does not work for Rational since in general the square root of a rational number is not rational. The only thing you could would use a Vector<Float> instead. You could then translate into Vector<Rational>, at the end, but then, your result will not exactly be the normalisation of the vector you started with (since this does not exist as a rational vector).

By the way: There is no need to transform the vector into a perl array before working with it. You can directly work with the polymake datatypes:

Code: Select all

$v=new Vector<Rational>([1,7,8,9,6,4,7,6,5]); $sum=new Rational(0); foreach (@$v) { $sum+=$_*$_; }
should produce the desired result.


Return to “Helpdesk”