473,672 Members | 2,666 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to overload sqrt in a module?

I would like to write a module that provides some mathematical functions
on top of those defined in math, cmath etc. but I would like to make it
work with "any" type that overloads the math functions.

Thus, I would like to write:

module_f.py
----
def f(x):
""" Compute sqrt of x """
return sqrt(x)
from math import *
import module_f
module_f.f(3) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "module_f.p y", line 2, in f
return sqrt(x)
NameError: global name 'sqrt' is not defined

I understand why sqrt is not in scope, but my question is: what is the
best way to do this?

Here is one fairly ugly solution:

module_g.py
-----------
def g(x,math):
return math.sqrt(x)
import math, cmath, module_g
module_g.g(2,ma th) 1.4142135623730 951 module_g.g(-2,cmath)

1.4142135623730 951j

I am sure there is a better way of doing this that makes use of the
type of the argument (Dynamical scoping would solve the
problem but we don't want to go there...). Note that the following
function would work fine

def f(x):
return abs(x)

because of the special member __abs__ attached to the type. There is no
corresponding member for sqrt, sin etc.

What is the "proper" pythonic way to do this?

Michael.
Mar 3 '06 #1
13 3767
Michael McNeil Forbes wrote:
I would like to write a module that provides some mathematical functions
on top of those defined in math, cmath etc. but I would like to make it
work with "any" type that overloads the math functions.

Thus, I would like to write:

module_f.py
----
def f(x):
""" Compute sqrt of x """
return sqrt(x)
from math import *
import module_f
module_f.f(3)


Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "module_f.p y", line 2, in f
return sqrt(x)
NameError: global name 'sqrt' is not defined

I understand why sqrt is not in scope, but my question is: what is the
best way to do this?


You need to import math in the module that uses it. Imports in one
module don't (in general) affect the variables available in another module.

module_f.py
----
from math import sqrt # more explicit than from math import *
def f(x):
""" Compute sqrt of x """
return sqrt(x)

Kent
Mar 3 '06 #2
>> I would like to write a module that provides some mathematical functions on
top of those defined in math, cmath etc. but I would like to make it work
with "any" type that overloads the math functions.

Thus, I would like to write:

module_f.py
----
def f(x):
""" Compute sqrt of x """
return sqrt(x)
> from math import *
> import module_f
> module_f.f(3)


Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "module_f.p y", line 2, in f
return sqrt(x)
NameError: global name 'sqrt' is not defined

I understand why sqrt is not in scope, but my question is: what is the best
way to do this?


You need to import math in the module that uses it. Imports in one module
don't (in general) affect the variables available in another module.

module_f.py
----
from math import sqrt # more explicit than from math import *
def f(x):
""" Compute sqrt of x """
return sqrt(x)

Kent


I know, but the point is that I want to allow the user of the module to be
able to specify which sqrt function should be used depending on the type
of x. Importing math in the module would prevent the user from using f()
with complex types (or dimensioned types for another example).

That is why I suggested the ugly, but functional solution

module_g.py
-----------
def g(x,a_math):
"""Compute sqrt of x using a_math.sqrt)
return a_math.sqrt(x)

The user can at least specify to use cmath instead of math:
import cmath, module_g
module_g.g(8j,c math)

(2+2j)

Michael.

Mar 3 '06 #3
Michael McNeil Forbes wrote:
Here is one fairly ugly solution:

module_g.py
-----------
def g(x,math):
return math.sqrt(x)

import math, cmath, module_g
module_g.g( 2,math)
1.4142135623730 951
module_g. g(-2,cmath)


1.4142135623730 951j

I am sure there is a better way of doing this that makes use of the
type of the argument (Dynamical scoping would solve the
problem but we don't want to go there...). Note that the following
function would work fine

def f(x):
return abs(x)

because of the special member __abs__ attached to the type. There is no
corresponding member for sqrt, sin etc.

What is the "proper" pythonic way to do this?


Use the appropriate library which already implements the features you want.

In [8]: class A(object):
...: def __init__(self, x):
...: self.x = x
...: def sqrt(self):
...: return 2*self.x
...:
...:

In [9]: a = A(10)

In [10]: import numpy

In [11]: numpy.sqrt(a)
Out[11]: 20

In [12]: numpy.sqrt(10)
Out[12]: 3.1622776601683 795

In [13]: numpy.sqrt(10j)
Out[13]: (2.236067977499 7898+2.23606797 74997898j)

--
Robert Kern
ro*********@gma il.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Mar 3 '06 #4
> Michael McNeil Forbes wrote:
Here is one fairly ugly solution:

module_g.py
-----------
def g(x,math):
return math.sqrt(x)

> import math, cmath, module_g
> module_g.g(2,ma th)
1.4142135623730 951
> module_g.g(-2,cmath)


1.4142135623730 951j

What is the "proper" pythonic way to do this?

On Thu, 2 Mar 2006, Robert Kern wrote:
Use the appropriate library which already implements the features you want.

In [8]: class A(object):
...: def __init__(self, x):
...: self.x = x
...: def sqrt(self):
...: return 2*self.x
...:
...:

In [9]: a = A(10)

In [10]: import numpy

In [11]: numpy.sqrt(a)
Out[11]: 20

In [12]: numpy.sqrt(10)
Out[12]: 3.1622776601683 795

In [13]: numpy.sqrt(10j)
Out[13]: (2.236067977499 7898+2.23606797 74997898j)

--
Robert Kern


Thanks. This solution is essentially to make sure that all "numeric"
objects have .sqrt etc. members, and then use a library which check
against builtin types and custom types with these extensions.

That works, as long as the appropriate library exists (or I write it
myself) (and this works in my case: I did not realize that the numpy/scipy
functions worked this way.)

Are there any other more generic solutions (without having to write
"custom" functions like numpy.sqrt)?

Michael
Mar 3 '06 #5
Michael McNeil Forbes wrote:
Are there any other more generic solutions (without having to write
"custom" functions like numpy.sqrt)?


No. *Someone* always has to write those "custom" functions. In the case of len()
and abs(), that someone was Guido. For numpy.sqrt(), that someone was Travis
Oliphant. For anything else you want, that someone is probably you.

--
Robert Kern
ro*********@gma il.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Mar 3 '06 #6
>> Are there any other more generic solutions (without having to write
"custom" functions like numpy.sqrt)?


No. *Someone* always has to write those "custom" functions. In the case of len()
and abs(), that someone was Guido. For numpy.sqrt(), that someone was Travis
Oliphant. For anything else you want, that someone is probably you.


Thanks Guido! Thanks Travis:-)

What I was thinking was: is there some way to pass a parameter to the
module on import so that the module can then use the correct environment.

If I could pass a dictionary to the module with all of the overloaded
functions, then they could become part of the module's environment and
used appropriately. I could not find a way of passing such a dictionary.

Michael.
Mar 3 '06 #7
> On Thu, 2 Mar 2006 16:12:53 -0800, Michael McNeil Forbes wrote:
I would like to write a module that provides some mathematical functions
on top of those defined in math, cmath etc. but I would like to make it
work with "any" type that overloads the math functions.
On Fri, 3 Mar 2006, Dennis Lee Bieber wrote: Since Python doesn't dispatch based on parameter types, there are
only two choices that I can see...

Either the CALLER already knows what the arguments are, and has
coded an explicit call to the version of the function desired...
The caller does know in my case, but wants to reuse old code that performs
a complicated computation using the standard math functions. I was
thinking that maybe there was some way for the caller to pass the
appropriate functions to the module on import, but could not find a way of
doing this.
OR, the caller imports and calls your special module, and your
special module has to import ALL possible override modules and supply a
function that determines which of the modules is to be used...


This is essentially what numpy.sqrt() etc. does as pointed out by Robert
Kern. The numpy.sqrt() seems to check if the argument is real, complex,
or some other type and calls either math.sqrt, cmath.sqrt or x.sqrt()
appropriately. This works for my problem: I just wondered if there was a
more generic solution without having to do this work.

Thanks,
Michael.
Mar 3 '06 #8
On Thu, 02 Mar 2006 19:24:48 -0800, mforbes wrote:

[snip]
I know, but the point is that I want to allow the user of the module to be
able to specify which sqrt function should be used depending on the type
of x. Importing math in the module would prevent the user from using f()
with complex types (or dimensioned types for another example).


If I don't misunderstood the problem, you can define an "init" method for
your module_g

(code not tested)

module_g.py
-----------

_functions = {}
def init(mathmodule ):
_function['sqrt'] = getattr(mathmod ule, 'sqrt', None)

def _get(name):
try:
return _functions[name]
except KeyError:
raise TypeError("you have to initialize module_g")

def sqrt(x):
return _get('sqrt')(x)

main.py
-------

import math
import module_g

module_g.init(m ath)
print module_g.sqrt(2 )
HTH

Mar 3 '06 #9
On Thu, 02 Mar 2006 22:35:51 -0800, Michael McNeil Forbes wrote:
What I was thinking was: is there some way to pass a parameter to the
module on import so that the module can then use the correct environment.

If I could pass a dictionary to the module with all of the overloaded
functions, then they could become part of the module's environment and
used appropriately. I could not find a way of passing such a dictionary.


Not on import, but you can do this:
import my_module
my_module.set_e nvironment("mat h") # or cmath, or numeric, or whatever

Your my_module will be like this:

# Warning: untested code.
ENVIRON = None # global variables sometimes have their uses

def f(x):
if ENVIRON is None:
raise ValueError("Uni nitialised module!")
# or use a custom exception
return ENVIRON.sqrt(x)

def set_environment (name):
global ENVIRON
ENVIRON = __import__(name )
Does this help?
--
Steven.

Mar 3 '06 #10

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

Similar topics

6
12042
by: Equis Uno | last post by:
Hi there, I just figured out how to use __add__() to overload the "+" operator for objects of a class. According to googel queries, I see other functions available to me for overloading other operators: __mul__(), __sub__(), ...
10
7318
by: pauldepstein | last post by:
I am writing a program which will use the ceiling and floor of square roots. If a positive integer is an exact square (and is not overly huge), does sqrt return an integer-valued real? Or might the sqrt function tell me that, for example, sqrt(1024) = 31.99999999999999999999999 You might say "try it". The problem is that I can't try infinitely
7
6767
by: Aric | last post by:
Hi, I'm a bit new to programming in general, really I've just picked it up as a hobby, and so I've started by reading "Practical C Programming" by Steve Oualline. Things have been going fine in the book until I reached exercise 6-1 in the book, which reads: Write a program to find the square of the distance between two points. (For a more advanced problem, find the actual distance. This problem involves using the standard function...
13
2723
by: Vladimir Granitsky | last post by:
Hi guys, Please, look at the code below and try to step into it. The compiled code calls the loosely typed method public void Method1(object o) !?!? Am I right that C# compiler does wrong overload resolution ? I've used parameters of type object and string here, just to illustrate the problem. Really I have a bit more deep inheritance graph, and the things get more interesting if the strongly typed overload is like override public void...
12
6309
by: Thomas Zhu | last post by:
hello all, n is an 32bit-integer, how to calculate sqrt(n) I know high(n) is the the value, but how to use bit operation to implement this function. thanks in advance. yours Yin
13
4953
by: siggi | last post by:
Hi all, this is a newbie question on : Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on win32 PC with WinXP In http://www.python.org/doc/2.3.5/lib/module-math.html I read:
30
4025
by: copx | last post by:
I am writing a program which uses sqrt() a lot. A historically very slow function but I read on CPUs with SSE support this is actually fast. Problem: C's sqrt() (unlike C++ sqrt()) is defined to work on doubles only, and early versions of SSE did not support double precision. The CPU requirement "something with at least first generation SEE support" (everything from P3/Athlon XP and up) is acceptable for me. However, requiring a CPU which...
13
10510
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, Why does Math.Sqrt() only accept a double as a parameter? I would think it would be just as happy with a decimal (or int, or float, or ....). I can easily convert back and forth, but I am interested in what is going on behind the scenes and if there is some aspect of decimals that keep them from being used in this calculation. Thanks! Ethan Ethan Strauss Ph.D.
6
4159
by: Blue sky | last post by:
Hi ,I think the follow program is right in logical But why the compiler output :"square:declared identifier" #include<stdio.h> #include<math.h> int main() { double x1;
0
8506
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
8948
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8852
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...
0
8701
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
7482
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...
1
6261
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4251
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2847
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
2
2098
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.