473,738 Members | 2,645 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dot products

HI.
I want to compute dot product of two vectors stored as lists a and b.a
and b are of the same length.

one simple way is
sum(a[i]*b[i] for i in range(len(a)))

another simple way is
ans=0.0
for i in range(len(a)):
ans=ans+a[i]*b[i]

But is there any other way which is faster than any of the above. (By
the way profiling them i found that the second is faster by about 30%.)
rahul

Jul 18 '05
12 8126
[Rahul].
I want to compute dot product of two vectors stored as lists a and b.a
and b are of the same length.

one simple way is
sum(a[i]*b[i] for i in range(len(a)))

another simple way is
ans=0.0
for i in range(len(a)):
ans=ans+a[i]*b[i]

But is there any other way which is faster than any of the above.


Yes:
from itertools import imap
from operator import mul
ans = sum(imap(mul, a, b))


Doh! We all missed it.

If your vector length is known in advance (and it often is in some apps), the
simplest and fastest approach is:

a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
C:\pydev>python timedot.py 3
0.32 sec: a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
1.38 sec: sum(a[i]*b[i] for i in xrange(len(a)))
1.32 sec: sum(x*y for x,y in izip(a,b))
1.62 sec: sum(x*y for x,y in zip(a,b))
0.75 sec: sum(imap(mul, a, b))
1.04 sec: sum(map(mul, a, b))

Raymond Hettinger
Jul 18 '05 #11
[Rahul].
I want to compute dot product of two vectors stored as lists a and b.a
and b are of the same length


from scipy import dot
ans=dot(a,b)

This times faster than the alternatives I have seen mentioned so far,
given scipy.

Cheers,
Alan Isaac
Jul 18 '05 #12
"Alan G Isaac" <ai****@america n.edu> wrote in message
news:10******** *****@corp.supe rnews.com...
This times faster than the alternatives I have seen mentioned so far,
given scipy.


Actually, since I am new to 'timeit', I probably should check that
I am not overlooking something. Especially since I see an order
of magnitude difference in performance. Does the code below
give the right comparisons?

Thanks,
Alan Isaac

#-------------------------------------------------------------
import timeit
env1='''
from operator import mul
from itertools import imap
def innerprod(x,y):
return sum(imap(mul,x, y))
from scipy import rand
x=rand(50); y=rand(50)
'''
env2='''
from operator import mul
from itertools import imap
from scipy import rand
x=rand(50); y=rand(50)
'''
env3='''
from scipy import rand,dot
x=rand(50); y=rand(50)
'''
t1=timeit.Timer ("innerprod(x,y )",env1)
t2=timeit.Timer ("sum(imap(mul, x,y))",env2)
t3=timeit.Timer ("dot(x,y)",env 3)
trials=1000
print t1.repeat(2,tri als) #about 0.1 seconds
print t2.repeat(2,tri als) #about 0.1 seconds
print t3.repeat(2,tri als) #about 0.01 seconds

Jul 18 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1486
by: frizzle | last post by:
Hi there I have a products site with a mysql backend. I have two tables: 1 with series, 1 with products belonging to certain series. Series looks like: - id - kind
0
3258
by: Ralph Guzman | last post by:
TASK: I have to generate a report with all categories, subcategories and products in database. PROBLEM: I want to write one query that will return: 1. category 2. subcategory: determined by parent_id 3. products in each category or subcategory.
2
3130
by: Hohn Upshew | last post by:
I need some help to build a report enumerating the products in descending order depending on the sum of liters. In this way i can view the top products sold for a given period.But i fail to do it. In my query i have build a total as follows SELECT products.Productid, products.grade, products.size, Sum(.liters) AS SumOfliters, orders.invoicedate FROM products INNER JOIN ((affiliates INNER JOIN Customers ON
1
2783
by: Mark | last post by:
My Category and Product tables look like: TblCategory CategoryID Category TblProduct ProductID CategoryID Product
6
3103
by: Paul T. Rong | last post by:
Dear all, Here is my problem: There is a table "products" in my access database, since some of the products are out of date and stopped manufacture, I would like to delete those PRODUCTS from the table, but I was not allowed to do that, because "there are records related with those PRODUCTS in other tables (e.g. in table "ORDER_DETAIL").
2
1916
by: TD | last post by:
I have this expression in the criteria section of a query: IIf(Forms!frmReports!cboProductID="<ALL PRODUCTS>",. Like "*",Forms!frmReports!cboProductID) (the syntax of the above expression may not be exact because I'm trying to write it from memory us now) I have a form with a combo box that I fill from a Union query that adds the phrase "<ALL PRODUCTS>" so that when you click on this combo box
24
1821
by: Rob R. Ainscough | last post by:
I was reading yet another book on .NET - VB 2005 Professional (wrox) and read the statement; "Microsoft has staked their future on .NET and publicly stated that henceforth almost all their research and development will be done on this platform. It is expected that, eventually, almost all Microsoft products will be ported to the .NET platform." So I thought about this statement for a minute -- then I realized that I have ALL...
9
1478
by: Earl | last post by:
I have somewhat of an interesting scenario: The form allows the user to select a service, which populates a a grid of product information related to that service ("service grid"). The user can then select from the products in the first grid and those choices populate the second "choices grid". The product grid is bound to a strongly-typed dataset table which can be filled in a couple of different ways. More on this shortly.
0
908
by: shapper | last post by:
Hello, I am displaying a list of products. I created a model using Linq To SQL. The List method is as follows: public void List(int? page) { dt.Products = (from p in db.Products orderby p.UnitPrice
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9259
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.