Is there any efficient easy way to compare two lists with the same length with Mathematica?

前端 未结 5 881
感情败类
感情败类 2021-02-13 23:41

Given two lists A={a1,a2,a3,...an} and B={b1,b2,b3,...bn}, I would say A>=B if and only if all ai>=bi.

There is

5条回答
  •  渐次进展
    2021-02-14 00:41

    Method 1: I prefer this method.

    NonNegative[Min[a - b]]
    

    Method 2: This is just for fun. As Leonid noted, it is given a bit of an unfair advantage for the data I used. If one makes pairwise comparisons, and return False and Break when appropriate, then a loop may be more efficient (although I generally shun loops in mma):

    result = True;
    n = 1; While[n < 1001, If[a[[n]] < b[[n]], result = False; Break[]]; n++]; result
    

    Some timing comparisons on lists of 10^6 numbers:

    a = Table[RandomInteger[100], {10^6}];
    b = Table[RandomInteger[100], {10^6}];
    
    (* OP's method *)
    And @@ Table[a[[i]] >= b[[i]], {i, 10^6}] // Timing
    
    (* acl's uncompiled method *)
    And @@ Thread[a >= b] // Timing
    
    (* Leonid's method *)
    lessEqual[a, b] // Timing
    
    (* David's method #1 *)
    NonNegative[Min[a - b]] // Timing
    

    timings 2


    Edit: I removed the timings for my Method #2, as they can be misleading. And Method #1 is more suitable as a general approach.

提交回复
热议问题