Usually when I've seen the sum function used, it has taken an argument within it's parentheses. What exactly does it do in the following, and what is the point of it?
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b)
print(b.grad_fn)
Related
from math import sqrt
def factor(a, b, c):
x1 = (-1 * b) + sqrt(b * b - (4 * a * c))
x2 = (-1 * b) - sqrt(b * b - (4 * a * c))
solution1 = (x1 / (2 * a))
solution2 = (x2 / (2 * a))
expression1 = ['x', (-1 * solution1)]
expression2 = ['x', (-1 * solution2)]
return expression1, expression2
print(factor(1, -17, 12))
I cannot figure out how to replace the values in the list to make the output look cleaner. I have tried arranging the values in different orders and adding strs to make it look better, but to no avail.
How can I make the output look like (x - 16.2)(x - 0.73) instead of (['x', -16.262087348130013], ['x', -0.7379126518699879])? I have not been successful in removing the unnecessary characters from the output.
I just want to remove the bracets and quotes.
Here's a painfully spread out (and ugly) solution, but one which should be useful as you learn the formatting and other tricks required to get this exactly as you want:
def pretty_product(e1, e2):
a = e1[0]
op1 = '+' if e1[1] >= 0 else '-'
b = e1[1]
c = e2[0]
op2 = '+' if e2[1] >= 0 else '-'
d = e2[1]
return f'({a} {op1} {abs(b):.2f})({c} {op2} {abs(d):.2f})'
print(pretty_product(['x', 2567.235235], ['y', -423.12313124214]))
Result is:
(x + 2567.24)(y - 423.12)
Note: if you want to suppress a possible + 0.00 you have more code to write, but it should be easy to add, I think. :)
You can use f-string
your_tuple = (solution1, solution2)
print(f'(x - {your_tuple[0]})(x - {your_tuple[1]})')
I read that if I have the following expression:
variable = variable op expression
It can be simplified and shown as follows:
variable op= expression
For example: i = i + 2 * j --> i += 2 * j
However, I have used the previous example in a = a / 2 * b --> a /= 2 * b
Let a=6 and b=3. Using both values in a=a/2*b, the output is 9. However, in the case of a /= 2* b, the output is 1
This is because you are changing the order of operations.
a = a / 2 * b is interpreted as "Divide a by 2, then multiply by b, then store the result in a", or a = (a / 2) * b.
a /= 2 * b is interpreted as "Multiply 2 by b, then divide a by the result, and store the final result in a", or a = a / (2 * b).
I hope this helps.
I have got a function:
def euler9():
for b in range(1, 500):
a = (500000 - 1000 * b) / (1000 - b)
if a % 1 == 0:
print(b * a * (1000 - a - b))
And I want to make it in one line like
x*x for x in range(1,1)
This is what I have done:
def euler9():
print([b * a * (1000 - a - b) for b in range(1, 500) for a in (500000 - 1000 * b) / (1000 - b) if a % 1 == 0])
but I do not know what am I doing wrong. I have got an error:
TypeError: 'float' object is not iterable
for is for iteration (looping). When you say for b in range(1, 500) you are not setting b = range(1, 500), since that would make b a list. You are extracting each individual value and using them one at a time. You cannot extract values from a float.
Python has no syntax for simple assignment in list comprehensions, but you can work around that by putting the value inside a single-element list, thus making it iterable:
[b * a * (1000 - a - b) for b in range(1, 500) for a in [(500000 - 1000 * b) / (1000 - b)] if a % 1 == 0]
(You can put print(...) around the initial expression if you want but I assume you want to actually use the values)
But don't ever do this, it's hard to read and unnecessary.
Here for a in (500000 - 1000 * b) / (1000 - b) you are trying to iterate over a float number which is the result of a devision.
As a quick fix try this:
def euler9():
print([b * ((500000 - 1000 * b) / (1000 - b)) * (1000 - ((500000 - 1000 * b) / (1000 - b)) - b)
for b in range(1, 500) if ((500000 - 1000 * b) / (1000 - b)) % 1 == 0])
But, as you see it gets a bit messy that way, and it is recommended to use loops instead of list comprehension when things get complicated.
Turn it into a generator by changing print to yield:
def euler9():
for b in range(1, 500):
a = (500000 - 1000 * b) / (1000 - b)
if a % 1 == 0:
yield (b * a * (1000 - a - b))
Then you can access it as a list comprehension:
print [x for x in euler9()]
I really don't know how to write this correctly. This is how I tried:
def is_cardano_triplet(a, b, c):
f = lambda x: x ** 1. / 2
g = lambda x: x ** 1. / 3
return g(a + b*f(c)) + g(a - b*f(c)) == 1
print is_cardano_triplet(2,1,5) # I should get True
I should get True for 2, 1, 5, but I'm not. What's wrong with my function?
Doing a few calculations, I found out that:
and therefore:
Now, due to floating point arithmetic being imprecise on binary-based systems for known reasons, the first formula is pretty hard to compute precisely. However, the second one is much easier to compute without floating point precision errors since that it doesn't involve irrational functions and a, b and c are integers.
Here's the smart solution:
def is_cardano_triplet(a, b, c):
return (a + 1)**2 * (8*a - 1) - 27*b**2*c == 0
>>> is_cardano_triplet(2, 1, 5)
True
The power operator (**) has a higher priority than the division one (/). So you need to set parentheses:
f = lambda x: x ** (1./3)
Still, floating point operations are not exact, so you have to compare with some small uncertainty:
def is_cardano_triplet(a, b, c):
f = lambda x: x ** (1. / 2)
g = lambda x: x ** (1. / 3)
return abs(g(a + b*f(c)) + g(a - b*f(c)) - 1) < 1e-10
Now you get the problem, that negative numbers are only allowed for roots of odd numbers, but floating points aren't exact, so you have to handle negative numbers by hand:
def is_cardano_triplet(a, b, c):
f = lambda x: x ** (1. / 2)
g = lambda x: (-1 if x<0 else 1) * abs(x) ** (1. / 3)
return abs(g(a + b*f(c)) + g(a - b*f(c)) - 1) < 1e-10
Now
print is_cardano_triplet(2,1,5)
results in True.
This may not be a question, just an observation, but is sympy supposed to work this way.
I have a two complicated expression, A and E, and I am trying to find out if they are equivalent. If I simplify one, say E, and use Eq(A,E) it does not return True, but the two separated with "==". If would have expected that sympy would be smart enough to work out they are equal. Eq(simplify(A),E) returns True. Here is the code ...
from sympy import *
B = symbols('B')
C = symbols('C')
F = symbols('F')
G = symbols('G')
H = symbols('H')
A = (B - C)*(G*(B + C) - (B - C - F)*H)**2
D = 2*(B**2+B*F-C**2)**2
E = A/D
ED=simplify(E*D)
print("E*D= {0}").format(str(ED))
print("A = {0}").format(str(A))
print("0 = {0}").format(str(simplify(A-ED)))
print("T = {0}").format(Eq(A,ED))
print("T = {0}").format(Eq(simplify(A),ED))
and the output
E*D= (B - C)*(G*(B + C) + H*(-B + C + F))**2
A = (B - C)*(G*(B + C) - H*(B - C - F))**2
0 = 0
T = (B - C)*(G*(B + C) - H*(B - C - F))**2 == (B - C)*(G*(B + C) + H*(-B + C + F))**2
T = True
Note the -H versus +H in the last expression.
Equality does not do any simplification and two objects are identical only if they are structurally (not mathematically) zero. Proving mathematical equality (in general) is not a simple problem so if they aren't identical (as in this case) SymPy doesn't even begin chasing the "equality rabbit" to its hole :-). This is the expected behavior. If you want to let SymPy try some simplification on its own, try using the equals method:
>>> A.equals(simplify(E*D))
True