File: Vector3.pm

package info (click to toggle)
algotutor 0.8.6-3
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 580 kB
  • sloc: perl: 2,563; makefile: 41; php: 24; sh: 1
file content (49 lines) | stat: -rw-r--r-- 1,030 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Author:  Chao-Kuei Hung
# For more info, including license, please see doc/index.html

package Vector3;
# 3-d Vector

use strict;
use Carp;
use vars qw(@ISA);
@ISA = qw(Vector);

use Vector;

sub cross {
# cross product
    my ($self, $other) = @_;
    return Vector->new(
	$self->y*$other->z-$self->z*$other->y,
	$self->z*$other->x-$self->x*$other->z,
	$self->x*$other->y-$self->y*$other->x,
    );
}

sub rotate_around {
# rotate $self around $axis by $th
    my ($self, $axis, $th) = @_;

    my ($x, $r, $p);
    $r = $axis->norm();
    return $self if $r < 1e-5;
    $x = $axis->pw_div($r);
    $r = $x->pw_mul($self->dot($x));
    $p = $self - $r;
    return $r + $p->pw_mul(cos($th)) + $x->cross($p)->pw_mul(sin($th));
}

if ($0 =~ /Vector3.pm$/) {
# being tested as a stand-alone program, so run test code.
    my ($p, $q);
    $p = Vector3->new(1,1,0);
    $q = Vector3->new(1,1,1);
    print $p->cross($q), "\n";
    # ans: [1, -1, 0]
    print $p->rotate_around($q, atan2(1,1)*8/3), "\n";
    # ans: [0, 1, 1]
}

1;