QUIZ 7: Dot product

#TC1017 #QUIZ 7

The last of the quizzes. I wanted to import the lists from text files just to practice doing that, but I had a problem with the unknown sizes of the lists, turns out I only managed to get it working properly if I specify before hand how big each list is. Other wise it was a simple quiz for me since I was also working on my sudoku.

Captura.PNG

Source Code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int CheckIfFirstOpen(string list1){
ifstream ListOne;
ListOne.open(list1.c_str());

if (ListOne.is_open()){
return 1;
} else {
return 0;
}
}

int CheckIfSecondOpen(string list2){
ifstream ListTwo;
ListTwo.open(list2.c_str());

if (ListTwo.is_open()){
return 1;
} else {
return 0;
}
}

vector<int>ReadList1(string list1){
vector<int>List1(4);
ifstream ListOne;
ListOne.open(list1.c_str());

for (int i = 0; i < List1.size(); i++) {
ListOne >> List1[i];
}
return List1;
ListOne.close();
}
vector<int>ReadList2(string list2){
vector<int>List2(4);
ifstream ListTwo;
ListTwo.open(list2.c_str());

for (int i = 0; i < List2.size(); i++){
ListTwo >> List2[i];
}
return List2;
ListTwo.close();
}

int DotProduct (vector<int>List1, vector<int>List2){
int size = 4;
int sum;

for (int i = 0; i < size; i++){
sum += List1[i] * List2[i];
}
cout << “Dot product is ” << sum;
}

int main(){
string list1;
string list2;

cout << “Please enter the name of the first list:” << endl;
cin >> list1;
cout << “Please enter the name of the second list:” << endl;
cin >> list2;

while (CheckIfFirstOpen(list1) == 0) {
cout << “Unable to open first file.” << endl;
cout <<“Please enter the name of the first text:” << endl;
cin >> list1;
}
cout << endl;

while (CheckIfSecondOpen(list2) == 0) {
cout << “Unable to open second file.” << endl;
cout <<“Please enter

Continue reading “QUIZ 7: Dot product”

🅰 ⚫ 🅱

In this WSQ we had to create a function called dot_product that receives two lists of numbers. The function returns what is the dot product of the two lists.

This are some screenshots of my program in the terminal and atom.

Captura de pantalla 2016-05-11 a las 6.45.31 p.m.
Captura de pantalla 2016-05-11 a las 6.45.17 p.m.

 

and my link to github as always 👉https://github.com/mfcanov/Quiz07.git

          main-qimg-c595b1f6b65f0e00beddc89d7fec9c13

(Credit goes to http://www.qmed.com/mpmn/gallery/image/engineering-life-chose-me)

Quiz #7

PRODUCTO ESCALAR

vsca1b

“El producto escalar y el producto vectorial son las dos formas de multiplicar vectores que vemos en la mayoría de las aplicaciones de Física y Astronomía. El producto escalar de dos vectores se puede construir, tomando la componente de un vector en la dirección del otro vector y multiplicandola por la magnitud del otro vector”

http://hyperphysics.phy-astr.gsu.edu/hbasees/vsca.html

 

Este programa trata de poder calcular escalares, el producto punto o producto escalar consiste en la multiplicación de vectores para dar resultado un escalar, precisamente esto es lo que realizamos en este programa.

Hay 2 listas de números, la primera lista se trata de las componentes en “x” de los vectores, y la segunda lista se trata de las componentes en “y” de los vectores.

La función de este programa dentro del código se llama dot_product. El tamaño de los vectores tienen que ser del mismo tamaño.

Quiz 7

Link GitHub: Quiz #7

¡Vectores! – #Quiz7

Creo que nunca dejaré de ver estas cosas, los vectores nos están invadiendo. Primero en mi clase de física, después en la clase de Ken y al final en la película que vi al finalizar el día. ¡Esto es increíble!

Este Quiz incluía un repaso a las listas y su función importante en este lenguaje de programación. Esta tarea consistía en introducir datos y calcular el producto cruz entre ellos, el producto cruz también se conoce como producto vectorial y  es así:

220px-Cross_product_parallelogram.svg Obviamente incluye vectores así que mi código resultó en el siguiente:

import random

dot_product = 0

n = int(input("Por favor, inserta el valor de n: "))

v = [None] * n
w = [None] * n

for i in range(0, n):
v[i] = random.randint(1, 100)
w[i] = random.randint(1, 100)

print(v)
print(w)

for i in range(0, n):
dot_product = dot_product + v[i] * w[i]

print("El producto escalar entre los 2 vectores es de " + str(dot_product))

En este código me serví de la enorme base de datos en forma de vídeos que es Youtube, precisamente me ayudó (sin saberlo) un chico colombiano, si quieren ver el vídeo pueden dar click aquí.

Mi código como siempre, está a su disposición en Github para manipularlo y mejorarlo.

• Product

Este código, trataba de hacer dos listas o grupos donde se guarden diferentes números, pero los vectores tienen que ser del mismo tamaño , sino va a mostrar en pantalla que no es un numero.

Para hacer este código tuve que incluir las librerías iostream, y limits.

En mi función llamada dot_product, la función recibe los valores de los vectores uno y dos así como también, los dos tamaños de los vectores. Dentro de la función, mediante un If es cuando se van a comparar los tamaños de los dos arreglos. si el tamaño de los dos arreglos es el mismo, entonces se procede a sumar el producto de la misma posición de cada arreglo. finalmente, en la función se pide que regrese el resultado de la suma

En la función main, se pide al usuario que ingrese los números que quieres guardar en cada arreglo mediante un ciclo For (para cada lista; lista1 y lista2). Y se pide que muestre por pantalla la respuesta de esta suma mejor conocida como Producto Punto.

Este es el codigo: Código

Captura de pantalla 2016-04-22 10.56.53

Quiz 07 “Dot Product”

One usually learns this chapter in Physics, were we are suppose to get the dot product of two vectors to later get the magnitude of such vector. This can be calculated by multipling the axis values of the first vector with the corresponding axis value of the second vector. Example: V1[x1 , y1 , z1] & V2[x2 , y2 , z2]  then Dp = [x1*x2,y1*y2, z1*z2]. And then the Magnitude is calculated by the square root of  the sum of the values squared. Or something like that, I do not know, do not ask me how I am doing in physics.

knowledge

Why I am telling this? Because we have to make a program that does this for you of course! However, at the end, we are only going to calculate the sum of the Dot Product and not it’s magnitude, shame. Remember that you can check out Ken’s instructions with more precision in his TC101 blog post.

This was succesfully done by the use of two empty list that the user fills by using forin range and inputs inside that operation. After the two list are full, the program multiplies the content of the list by cardinality. Cardinality is used with the symble “[]” such as List1[Cardinality]. This means when cardinality = 1 then it will use the first value of list one and so on. We also had to make the use of conditionals since there is a possibility that the user has one list longer than the other. When that happens, there is a number that misses a pair from the other list to be multiplied by. In this case, the program returns ‘NaN’ which means ‘Not a Number’. This is how the program looks and runs, and remember to keep checking my Github since we

quiz07.png
Hey

Continue reading “Quiz 07 “Dot Product””