0

This is probably straightforward, elementary and whatever, but I can't manage to get it. I have 2 Nx1vectors u and w, which are composed by both negative and positive values. I am trying to compute w'u u'w , which should be a quadratic form. I should be able to write this like

t(w)%*%u%*%t(u)%*%w

However sometimes I get a negative value, depending on the values in the two vectors. This is not possible, since that thing is a quadratic form. I tried with

crossprod(w, u)%*%crossprod(u, w)

and

crossprod(w, u)*crossprod(u, w)

which gives positive and equal results. However, since I am dealing with Nx1vectors, I should also be able to write it as

`sum(w*u)^2`

which gives a positive value but different from the ones above.

So I guess I am doing something wrong somewhere. So, the question is: how can I express w'u u'w which is valid for both vectors and matrices ?

EDIT: here a csv file with the original vectors to reproduce exactly the same issue

Bob
  • 452
  • 6
  • 18
  • 1
    Would you please provide a reproducible example of your data. You can use `dput` or check this (http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – mallet Nov 25 '14 at 14:15
  • I could. But it does not matter, since the quadratic form must be positive no matter which the data is. And I apply that procedure for different vectors and for some it works, for others it does not. Hence the point is not the data. However, I will provide an example shortly – Bob Nov 25 '14 at 14:25
  • it is all about something to try your code with instead of generating random numbers – mallet Nov 25 '14 at 14:27
  • I added the csv.file. You can find it here http://www.filedropper.com/data_4 – Bob Nov 25 '14 at 14:33
  • I don't get negative results with your data. I obtain roughly the same value whatever procedure I follow. I guess the small differences are due to loss of precision. – nicola Nov 25 '14 at 14:52
  • t(w)%*%u%*%t(u)%*%w gives -2.031317e-29, which is negative. This brings problem when I go for sqrt( .. ) However, given the number of 0s, I think it is just as you say, machine approximation problems – Bob Nov 25 '14 at 14:58
  • me as well, I got positive values at all times. – mallet Nov 25 '14 at 15:04
  • Thanks people. It must definetly be the machine approximation issue due to loss of precision – Bob Nov 25 '14 at 15:05
  • just for you to check, I got this number 5.843948e-18 not -2.031317e-29 – mallet Nov 25 '14 at 15:08
  • I got the same. If you multiply every data * 1000 you get exactly the same results. Thanks – Bob Nov 25 '14 at 15:18

0 Answers0