What is wrong with this python function from “Programming Collective Intelligence”?

后端 未结 4 1035
梦如初夏
梦如初夏 2021-01-06 07:31

This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.

When I use this

4条回答
  •  半阙折子戏
    2021-01-06 07:59

    It looks like you may be unexpectedly using integer division. I made the following change and your function returned 1.0:

    num=pSum-(1.0*sum1*sum2/n)
    den=sqrt((sum1Sq-1.0*pow(sum1,2)/n)*(sum2Sq-1.0*pow(sum2,2)/n))
    

    See PEP 238 for more information on the division operator in Python. An alternate way of fixing your above code is:

    from __future__ import division
    

提交回复
热议问题