how to get real valule in R [duplicate] - python

I'm just learning R, so please forgive what I'm sure is a very elementary question. How do I take the real part of a complex number?

If you read the help file for complex (?complex), you will see a number of functions for performing complex arithmetic. The details clearly state
The functions Re, Im, Mod, Arg and Conj have their usual interpretation as returning the real part, imaginary part, modulus, argument and complex conjugate for complex values.
Therefore
Use Re:
Re(1+2i)
# 1
For the imaginary part:
Im(1+2i)
# 2
?complex will list other useful functions.

Re(z)
and
Im(z)
would be the functions you're looking for.
See also http://www.johnmyleswhite.com/notebook/2009/12/18/using-complex-numbers-in-r/

Related

Time-consuming substitution in sympy

I have a very long polynomial in Sympy that I want to substitute with numbers. But this substitution will take a lot of time, while the same polynomial in MATLAB software will be output in less than one second.
How can I solve this problem in Python?
I just tried for exapmle: polynomial.subs([(k11,9600000000.00000), (k12,3066000000.0000),...])
If you are looking for a numerical result, you probably want to look at lambdify, which converts the symbolic polynomial to a numerical function for faster evaluation...
f = lambdify(coefficient_list, polynomial)
result = f(*coefficient_values)

Z3 check python string satisfiability

Is there a way to check satisfiability of a python string like 'p or p -> p' in Z3 if you do not know the variable names before hand?
For example I have seen this:
p = Bool('p')
solve(Implies(Or(p, p), p))
However I cannot define the variables in Z3 in advance because the proposition is given to me as a string. How can I do this with z3?
I have also seen python's eval function but it seems I need to have the variable names defined in z3 of that prior too
Some questions to ponder: What would be the meaning of that string? What if it has syntax-errors in it? How do you discern what are the valid operators/variables? Do you allow just booleans, or other sorts as well? What about grouping, precedence, and associativity of operators?
Bottom line, if you want to go directly from a string, you really have no choice but to agree on a syntax and a semantics of what those strings mean. And the only way to do that is to write a parser for those strings, and "interpret" that result in the z3 context.
One choice is to "stick" to SMTLib, i.e., ask your input to be well-formatted SMTLib scripts. If you go with this choice, then z3 already have a built-in parser for them that you can readily use. See here: https://z3prover.github.io/api/html/namespacez3py.html#a09fe122cbfbc6d3fa30a79850b2a2414 But I'm pretty sure you'll find this rather ugly and not quite what you wanted. But this is the only "out-of-the-box" solution.
The proper way to handle this issue is to write a basic parser over boolean-expressions, whose syntax (and to some extent semantics) you'll have freedom to define however way you want. Also, this isn't a particularly difficult thing to do. If you're doing this in Python, you can use ply (https://www.dabeaz.com/ply/), or go with a hand-written recursive-descent parser (https://www.booleanworld.com/building-recursive-descent-parsers-definitive-guide/).
Feel free to explore and ask further questions; though make sure to tag them appropriately if it's about parsing strings in Python; which really have nothing to do with z3/z3py.

How do I fix this OverflowError?

I keep getting a "OverflowError: math range error". No matter what I input, the result is the same. I'm running Python 3.3, and it's finding the problem at the last line. How do I fix this? (Also, I don't want to hear anything about my overuse of parentheses. It is my preference for there to be this many.):
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
first_root=first_root-((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)/(3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)
I know you don't want to hear about your excessive use of parenthesis, but the problem is that you have the parenthesis in the wrong places. With the sheer number of parenthesis you used, it took a while to find the problem.
I think the following code is much cleaner, easier to debug, and vastly easier to maintain in the future. I also included what I think is the corrected version of your one-liner.
import math
a=float(input('a=?'))
b=float(input('b=?'))
c=float(input('c=?'))
d=float(input('d=?'))
critical_point_n=((-2*b)-math.sqrt(abs((4*(math.pow(b, 2)))-(12*a*c))))/(6*a)
first_root=critical_point_n-1
if first_root==0 and c==0:
first_root+=(-0.01)
for x in range(10):
f = a*first_root**3 + b*first_root**2 + c*first_root + d
fp = 3*a*first_root**2 + 2*b*first_root + c
first_root = first_root - (f/fp)
#first_root=first_root-(((a*(math.pow(first_root, 3)))+(b*(math.pow(first_root, 2))+(c*first_root)+d)))/((3*(a*(math.pow(first_root, 2))))+(2*(b*first_root))+c)
print(first_root)
You are overflowing the internal representation of floats. Use sys.float_info to check your system's limits for floating point numbers. http://docs.python.org/3.3/library/sys.html#sys.float_info
I recommend trying out your operations by "hand" on wolframalpha to see the magnitude of the actual values. http://www.wolframalpha.com/
The math range of functions work on doubles... so you're out of range for that - re-write as normal Python floats which will scale as needs be, or look at using decimal.Decimal which also has sqrt, power etc.. functions: http://docs.python.org/2/library/decimal.html

Python- stuck trying to create a "free hand" calculator

I'm trying to create a calculator program in which the user can type an equation and get an answer. I don't want the full code for this, I just need help with a specific part.
The approach I am trying to take is to have the user input the equation as a string (raw_input) and then I am trying to convert the numbers from their input to integers. After that I need to know how I can get the operands to do what I want them to do depending on which operand the user uses and where it is in the equation.
What are some methods I might use to accomplish this task?
Here is basically what I have right now:
equation_number = raw_input("\nEnter your equation now: ")
[int(d) for d in equation_number if d.isdigit()]
Those lines are just for collecting input and attempting to convert the numbers into integers. Unfortunately, it does not seem to be working very well and .isdigit will only work for positive numbers anyway.
Edit- aong152 mentioned recursive parsing, which I looked into, and it appears to have desirable results:
http://blog.erezsh.com/how-to-write-a-calculator-in-70-python-lines-by-writing-a-recursive-descent-parser/
However, I do not understand the code that the author of this post is using, could anyone familiarize me with the basics of recursive parsing?
The type of program you are trying to make is probably more complicated than you think
The first step would be separating the string into each argument.
Let's say that the user inputs:
1+2.0+3+4
Before you can even convert to ints, you are going to need to split the string up into its components:
1
+
2.0
+
3
+
4
This will require a recursive parser, which (seeing as you are new to python) maybe be a bit of a hurdle.
Assuming that you now have each part seperately as strings,
float("2.0") = 2.0
int(2.0) = 2
Here is a helper function
def num (s):
try:
return int(s)
except exceptions.ValueError:
return int(float(s))
instead of raw_input just use input because raw_input returns a string and input returns ints
This is a very simple calculator:
def calculate():
x = input("Equation: ")
print x
while True:
calculate()
the function takes the input and prints it then the while loop executes it again
im not sure if this is what you want but here you go and also you should make a way to end the loop
After using raw_input() you can use eval() on the result to compute the value of this string. eval() evaluates any valid Python expression and returns the outcome.
But I think this is not to your liking. You probably want to do more by yourself.
So I think you should have a look at the re module to split the input using regular expressions into tokens (sth like numbers and operators). After this you should write a parser which gets the token stream as input. You should decide whether this parser shall just return the computed value (e. g. a number) or maybe an abstract syntax tree, i. e. a data structure which represents the expression in an object-oriented (instead of character-oriented) way. Such an Absy could then be evaluated to get the final result.
Are you familiar with regular expressions? If not, it's probably a good idea to first learn about them. They are the weak, non-recursive cousin of parsing. Don't go deep, just understand the building blocks — A then B, A many times, A or B.
The blog post you found is hard because it implements the parsing by hand. It's using recursive descent, which is the only way to write a parser by hand and keep your sanity, but it's still tricky.
What people do most of the time is only write a high level grammar and use a library (or code generator) to do the hard work of parsing.
Indeed he had an earlier post where he uses a library:
http://blog.erezsh.com/how-to-write-a-calculator-in-50-python-lines-without-eval/
At least the beginning should be very easy. Things to pay attention to:
How precedence arises from the structure of the grammar — add consists of muls, not vice versa.
The moment he adds a rule for parentheses:
atom: neg | number | '(' add ')';
This is where it really becomes recursive!
6-2-1 should parse as (6-2)-1, not 6-(2-1). He doesn't discuss it, but if you look
carefully, it also arises from the structure of the grammar. Don't waste tome on this; just know for future reference that this is called associativity.
The result of parsing is a tree. You can then compute its value in a bottom-up manner.
In the "Calculating!" chapter he does that, but the in a sort of magic way.
Don't worry about that.
To build a calculator yourself, I suggest you strip the problem as much as possible.
Recognizing where numbers end etc. is a bit messy. It could be part of the grammar, or done by a separate pass called lexer or tokenizer.
I suggest you skip it — require the user to type spaces around all operators and parens. Or just assume you're already given a list of the form [2.0, "*", "(", 3.0, "+", -1.0, ")"].
Start with a trivial parser(tokens) function that only handles 3-element expressions — [number, op, number].
Return a single number, the result of the computation. (I previously said parsers output a tree which is processed later. Don't worry about that, returning a number is simpler.)
Write a function that expects either a number or parentheses — in the later case it calls parser().
>>> number_or_expr([1.0, "rest..."])
(1.0, ["rest..."])
>>> number_or_expr(["(", 2.0, "+", 2.0, ")", "rest..."])
(4.0, ["rest..."])
Note that I'm now returning a second value - the remaining part of the input. Change parser() to also use this convention.
Now Rewrite parser() to call number_or_expr() instead of directly assuming tokens[0] and tokens[2] are numbers.
Viola! You now have a (mutually) recursive calculator that can compute anything — it just has to be written in verbose style with parens around everything.
Now stop and admire your code, for at least a day :-) It's still simple but has the essential recursive nature of parsing. And the code structure reflects the grammar 1:1 (which is the nice property of recursive descent. You don't want to know how the other algorithms look).
From here there many improvements possible — support 2+2+2, allow (1), precedence... — but there are 2 ways to go about it:
Improve your code step by step. You'll have to refactor a lot.
Stop working hard and use a parsing library, e.g. pyparsing.
This will allow you to experiment with grammar changes faster.

Could anyone help me with this python singpath program?

First of all, this is not for any class.
I have been working on these 2 programs for a long time and cannot make heads or tails of it. I really want to get past these problems so I can move onto other lessons.
"Create a function that transforms the prefix notation into postfix notation, and postfix notation into prefix notation. The function takes two arguments. The first is a string of an expression without spaces or syntax errors, and the second is another string contains all the operators. Characters not in the second string are regarded as operands. The lengths of all the operators and operands are 1, and all the operators are binary operators."
ex:
>>> fix_trans('ab33c2c11','abc')
'33b211cca'
and Convert to (reverse) Polish notation:
>>> toPolish('(3+5)*(7-2)',D,0)
'*+35-72'
Can you provide any examples of how far you've gotten with this, or what methods haven't worked for you? Also, are you familiar with the shunting-yard algorithm?

Categories