Advertisement
Guest User

Vect.java

a guest
Feb 13th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. //
  2. // Vect.java
  3. // This program is intended for a debugging exercise and was expressly
  4. // designed not to work. If you're my student you have permission to
  5. // use this code for the assignment in which it was given. Don't expect
  6. // it to work out of the box.
  7. // Copyright (c) 2013-2016 cmagnus. All rights reserved.
  8. //
  9. //package Debugging;
  10.  
  11. public class Vect {
  12. private static int MAXSIZE = 99;
  13. private float[] v = new float[MAXSIZE];
  14. private int size;
  15.  
  16. // if no arguments, create a vector of length 1
  17. public Vect()
  18. {
  19. size = 1;
  20. this.v = new float[1];
  21. v[0] = 0;
  22. }
  23.  
  24. // create a vector of length size
  25. public Vect(int length)
  26. {
  27. size = length;
  28. this.v = new float[size];
  29. for (int i = 0; i < size; i++)
  30. {
  31. v[i] = 0;
  32. }
  33. }
  34.  
  35. // make a Vect object from a vector of floats
  36. public Vect(float[] args)
  37. {
  38. size = args.length;
  39. this.v = new float[args.length];
  40. for (int i = 0; i < args.length; i++)
  41. {
  42. v[i] = args[i];
  43. }
  44. }
  45.  
  46. // sets value at index i to f
  47. public void setValue(int i, float f)
  48. {
  49. v[i] = f;
  50. }
  51.  
  52. // return value of index i
  53. public float getVect(int i)
  54. {
  55. return(v[i]);
  56. }
  57.  
  58. // sets value at index i to a random number (to generate test data)
  59. public void randVect(int i)
  60. {
  61. setValue(i, (int)(Math.random() * 10));
  62. }
  63.  
  64. // prints a Vect
  65. public void printVect()
  66. {
  67. System.out.print("{ ");
  68. for (int i = 0; i < v.length; i++)
  69. System.out.print("" + v[i] + " ");
  70. System.out.println("}");
  71. }
  72.  
  73. // returns size of Vect
  74. public int getSize()
  75. {
  76. return(size);
  77. }
  78.  
  79. // takes dot product of Vect and v2
  80. public float dotProduct(Vect v2)
  81. {
  82. // initialize f
  83. int f = 0;
  84.  
  85. // dot product requires vectors of equal length
  86. if (this.getSize() == v2.getSize())
  87. {
  88. // dot product of 2 vectors is v[0]*v2[0] + v[1]*v2[1] + ... v[size]*v2[size]
  89. for (int i = 0; i < this.getSize()-1; i++)
  90. {
  91. f += v[i] * v2.getVect(i);
  92. }
  93. }
  94. else
  95. {
  96. System.out.println("Dot Product requires vectors of equal length.");
  97. }
  98. return(f);
  99. }
  100.  
  101. } // end class vector
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement