This part of program on Python uses SymPy library.
As a result it's produces a value in sympy.core.add.Add class which is not capable with other parts of the program.
from sympy import *
x = symbols('x')
y = 1 - (0.1 * coeff1) / (x + 2) - sin(x) * (2 * x + coeff1)
yprime = y.diff(x)
How to convert sympy.core.add.Add class to ordinary float or int in order to use variable yprime in further calculations?
How about just ending your code with
yprime = float(yprime)
I think you can take a look at the documentation here http://docs.sympy.org/dev/modules/core.html#module-sympy.core.add
There are some functions starting with "as_" for the type sympy.core.add.Add, with which you can convert add.add into other formats and then change into float or int.
I just found the solution.
using yprime=float(yprime) won't work because yprime is an element of a class of numpy only.
But you can transform that element in order to make the python standard language be capable to read it.
try:
yprime=str(yprime)
#this will transform yprime to a string
yprime=eval(yprime)
#this will return a float or a int object so you can do calculations without any problem but make sure that the constants are well defined.
Related
I'm new to python and I have a doubt regarding a homework problem. I am unable to find the value of an expression in integer form.
The question is c=(6-3)*(2+7)/3.
What I have done is print("c=(6-3) * (2+7)/3=", (6-3) * (2+)/3)
I have gotten the value 9.0 so what expression should I write in order for me to get 9 and not 9.0?
Since you are using multiplication and division your answer gets converted to float, so at the end you simply have to convert it to integer.
So you can try this:
print("c=(6-3) * (2+7)/3=", int((6-3) * (2+7)/3))
I think that you are using Python 3 since you are getting a float when performing a regular division or multiplication. You have two possible options:
You can cast the result using the built-int int
print("c=(6-3) * (2+7)/3=", int((6 - 3) * (2 + 7) / 3))
You can use integer division //
print("c=(6-3) * (2+7)/3=", int((6 - 3) * (2 + 7) // 3))
In both cases the output will be:
c=(6-3) * (2+7)/3= 9
Is it possible to somehow override or overload the standard implementation of ints/numbers in python so that it acts like a 32-bit int.
a: int
a = 4076863488
>>> -218103808
Or is it possible to somehow define a variable that can't change type? Doing something like: x: int?
I want to do this because it's annoying to write ctypes.c_int32(n) on every bit operation and assignment. Especially since Python does not use 32 bits bitwise operands.
I know I'm basically trying to change the nature of the language. So maybe I'm asking what you would do if you had to do 32-bit stuff in python.
Some options:
Use Cython. You can declare a native 32-bit int type there, and you even get the advantage that pure numerical code gets compiled to (very) fast C code.
Use a numpy array of a single element: np.zeros((1,), dtype=np.int32). Provided you only ever use in-place operations (+=, *=, etc.), this will work like a 32-bit int type. Do be aware that if you ever use a regular binary operator (e.g. myint + 3), you might be subjected to type promotion or conversion, and the result will no longer be int32.
Use ctypes.c_int32. This comes built-in to Python, but supports no mathematical operations so you have to wrap and unwrap yourself (e.g. newval = c_int32(v1.value + v2.value)).
Use a library like fixedint (shameless plug), which provides fixed-integer classes that remain fixed size through operations rather than decaying to int. fixedint was specifically designed with fixed-width bitwise math in mind. In this case you would use fixedint.Int32.
Some less desirable options:
struct: Throws errors if your input is out of range. You can work around this with unpack('i', pack('I', val & 0xffffffff))[0], but that's really unwieldy.
array: Throws errors if you try to store a value out of range. Harder to work around than struct.
Manual bitmashing. With an unsigned 32-bit int, this is just a matter of adding & 0xffffffff a lot, which is not too bad. But, Python doesn't have any built-in way to wrap a value to a signed 32-bit int, so you'll have to write your own int32 conversion function and wrap all your operations with it:
def to_int32(val):
val &= ((1<<32)-1)
if val & (1<<31): val -= (1<<32)
return val
Demonstrations of your options:
Cython
cpdef int munge(int val):
cdef int x
x = val * 32
x += 0x7fffffff
return x
Save as int_test.pyx and compile with cythonize -a -i int_test.pyx.
>>> import int_test
>>> int_test.munge(3)
-2147483553
NumPy
import numpy as np
def munge(val):
x = val.copy()
x *= 32
x += 0x7fffffff
return x
def to_int32(val):
return np.array((val,), dtype=np.int32)
print(munge(to_int32(3)))
# prints [-2147483553]
ctypes
from ctypes import c_int32
def munge(val):
x = c_int32(val.value * 32)
x = c_int32(x.value + 0x7fffffff)
return x
print(munge(c_int32(3)))
# prints c_int(-2147483553)
fixedint
import fixedint
def munge(val):
x = val * 32
x += 0x7fffffff
return x
print(munge(fixedint.Int32(3)))
# prints -2147483553
I am currently working with Sympy 1.0 and Python 2.7, and my aim is to replace every numerical parameter in an expression with a symbol.
For example:
2 * x + 3 * y - 10 * z -> a * x + b * y - c * z
So far I used expression.atoms(Number) to obtain the list of numerical parameters, to later replace them either using .subs or by writing everything to string and using .replace. However, I am facing an issue with expressions such as:
expression = sympy.simpify("x - z")
Where -z is actually -1 * z if I analyze the expression as a tree...but -1 does not appear among the result of expression.atoms(Number), so I cannot replace it.
Even converting the expression to a string to then use .replace does not really help, as -1 * z is always written out as -z.
There is probably some solution that I overlooked, but so far I am stuck. Can you help me? Thank you in advance for your time.
In fact, it turns out I probably did a moronic error when I first tried to use .subs; as Patrick noted in the comments, .subs works perfectly in this case.
I'm using Sympy's sympify function to simplify 2 expressions so I can compare them for equality.
For example:
expr1 = sympify("(2 * x) + (x + 10)")
expr2 = sympify("(x + 10) + (x * 2)")
if expr1 == expr2:
print "Congrats those are essentially the same!"
However when using the form 2x as apposed to x*2 i get a parse exception eg:
expr1 = sympify("2x + (x + 10)")
Is there any way I can get sympy to understand the 2x form ?
If not, is there any other library that will allow this form ?
Well, you could modify the sympy lexer (or parser / grammar / whatever).
You could also wrap it with a function that transformed your input strings for you, using something like this:
>>> import re
>>> expr = '2x + 1'
>>> re.sub(r"(\d+)(\w+)", r"(\1 * \2)", expr)
'(2 * x) + 1'
But ask yourself why this notation isn't there to begin with.
For example, all of these are valid python, and though it's been a long while since I messed with sympy, I bet they mean something besides multiplication in sympy too:
0x32 # hex for 50
5e-3 # 0.005
2j # 2 * sqrt(-1) (so that one *is* multiplication, but by 1j, not j!)
15L # 15 (L used to represent long integers in python)
And what does x2 mean? Is it a variable named x2 or does it mean (x * 2). I purposely left this case out of the regular expression above because it's so ambiguous.
The development version of SymPy has the ability to parse such expressions. See http://docs.sympy.org/dev/modules/parsing#sympy.parsing.sympy_parser.implicit_multiplication_application. It is still not enabled by default in sympify, because sympify only does very basic extensions to the Python syntax (i.e., wrapping of numeric literals and undefined names, and converting ^ to **). But there is an example there that shows how to use it.
Note that this currently also applies implicit function application as well. Probably the two functionalities should be split up.
EDIT: Those functions are being split up in a pull request.
In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?
t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))
source
I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.