Created
November 9, 2018 22:08
-
-
Save JediKnightChan/5357a1b553cb758e4bb2bd28acc37437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"math" | |
) | |
type Vector struct { | |
Body []float64 | |
} | |
func (vector Vector) Norm() float64 { | |
norm := 0.0 | |
for _, x := range vector.Body { | |
norm += math.Pow(x, 2) | |
} | |
return norm | |
} | |
func (vector Vector) Size() int { | |
return len(vector.Body) | |
} | |
func (vector Vector) String() string { | |
return fmt.Sprintf("Vector: %v with size %v", vector.Body, vector.Size()) | |
} | |
func (vector1 Vector) AddVector(vector2 Vector) (Vector, error) { | |
err := check_vector_sizes_equal(vector1, vector2) | |
if err != nil { | |
return Vector{}, err | |
} | |
var new_body []float64 | |
for i := range vector1.Body { | |
new_body = append(new_body, vector1.Body[i] + vector2.Body[i]) | |
} | |
return Vector{new_body}, nil | |
} | |
func (vector Vector) MultiplyByInt(f float64) Vector { | |
var new_body []float64 | |
for i := range vector.Body { | |
new_body = append(new_body, vector.Body[i] * f) | |
} | |
return Vector{new_body} | |
} | |
func (vector1 Vector) DotProduct(vector2 Vector) (float64, error) { | |
err := check_vector_sizes_equal(vector1, vector2) | |
if err != nil { | |
return 0, err | |
} | |
result := 0.0 | |
for i := range vector1.Body { | |
result += vector1.Body[i] * vector2.Body[i] | |
} | |
return result, nil | |
} | |
func (vector1 Vector) CalculateAngleBetweenVectors(vector2 Vector) (float64, error) { | |
dot_product, err := vector1.DotProduct(vector2) | |
if err != nil { | |
return 0, err | |
} | |
err = check_vector_norms_non_zero(vector1, vector2) | |
if err != nil { | |
return 0, err | |
} | |
return math.Acos(dot_product / (vector1.Norm() * vector2.Norm())), nil | |
} | |
func check_vector_sizes_equal(vector1 Vector, vector2 Vector) error { | |
if vector1.Size() != vector2.Size() { | |
error_text := fmt.Sprintf("Vectors with different sizes: %v and %v", vector1, vector2) | |
return errors.New(error_text) | |
} | |
return nil | |
} | |
func check_vector_norms_non_zero(vectors ...Vector) error { | |
for _, vector := range vectors { | |
if vector.Norm() == 0 { | |
error_text := fmt.Sprintf("Vector %v has zero norm", vector) | |
return errors.New(error_text) | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment