我可以知道如何在Java中对两个向量求和吗?
public void CosineSimilarity(ArrayList<Integer> h,String a, Object[] array) throws Exception {
Vector value = new Vector();
double cos_sim=(cosine_similarity(vec1,vec2))*60/100;
System.out.println(cos_sim); //I get [0.333] and [0.358]
value.add(cos_sim);
CompareType(value,a,array);
}
这里的CompareType函数
public void CompareType(Vector value,String a,Object[] array ) throws Exception {
// TODO Auto-generated method stub
String k;
double c = 0;
String sql="Select Type from menu ";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
Vector value1 = new Vector();
while (rs.next())
{
k=rs.getString("Type");
if(a.equals(k))
{
c=10.0/100;
value1.add(c);
}
else
{
c=0;
value1.add(c);
}
}
System.out.println(value1); // I get [0.0] and [0.1]
Sum(value,value1);
ps.close();
rs.close();
conn.close();
}
我应该在下面的函数中写些什么,以便可以将两个值向量相加并返回两个总值?
private void Sum(Vector value, Vector value1) {
// TODO Auto-generated method stub
}
使用Java8流API可以轻松实现(此示例代码输出6.0
为1.0+2.0+3.0
:
/** setup test data and call {@link #sum(Vector)} */
public static void main(String[] args) {
Vector a = new Vector();
Vector b = new Vector();
a.add(1.0);
a.add(2.0);
b.add(3.0);
System.out.println(sum(a, b));
}
/** Sum up all values of two vectors */
private static double sum(Vector value, Vector value1) {
return sum(value) + sum(value1);
}
/** Sum up all values of one vector */
private static double sum(Vector value) {
return
// turn your vector into a stream
value.stream()
// make the stream of objects to a double stream (using generics would
// make this easier)
.mapToDouble(x -> (double) x)
// use super fast internal sum method of java
.sum();
}
有关如何使代码更好的一些想法:
sumA
andsumB
代替sum
and sum1
,等等。Collection
或List
接口。Vector
。(摘自官方javadoc:“如果不需要线程安全的实现,建议使用ArrayList代替Vector。”)本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句