Print x/2 as 1/2 x in Sympy - python

How can I tell Sympy to print x/2 as 1/2 x for example? I.e. print a fraction as 1 over the denominator times the numerator?

To do this properly you would have to write your own printer, I believe. To do this hackishly you might try:
mul = x/2
a, b = mul.as_two_terms()
if a.is_Rational and not a.is_Integer:
print (Mul(Symbol(str(a.p))/a.q, b, evaluate=False))
else:
print (mul)

Related

python How to convert the input value into a mathematical function

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2
You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!
You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

Power of 10 with Python Sympy and Latex

This is probably trivial, but I can't find the answer. Consider the following code:
from sympy import *
X = Symbol('X')
a=10
b=100
c=1000
d=10000
s = latex ( a*b*c*d / X )
print (s)
displays:
\frac{10000000000}{X}
And I would prefer
\frac{10^{10}}{X}
Is it possible ? Note that a, b, c and d are read from files. So values will change at each run. Then, following stuffs don't solve my problem:
n20 = Symbol('10')
neither
latex(S('10**10/X', evaluate=False))
>>> from sympy import *
>>> var('X')
X
>>> latex(S('10**20/X', evaluate=False))
'\\frac{10^{20}}{X}'
See https://github.com/sympy/sympy/wiki/Quick-examples.
EDIT: Your edited question differs considerably from the original. Here's an answer to it.
Because your input values might not be powers of ten r might not be. Consequently, when it is expressed as a power of ten its exponent might not be an integer; hence, the use of base ten logarithms.
from sympy import latex, sympify, Symbol
from math import log10
a=10
b=100
c=1000
d=10000
r = a * b * c * d
exponent = log10(r)
X = Symbol('X')
s = latex(sympify('10**{}/X'.format(exponent), evaluate=False))
print (s)
The result for these values of a, b, c and d is \frac{10^{10.0}}{X}.
All you need is a little help that will return your number with powers of 10 removed. Then wrap this in an unevaluated Mul and pass it to latex:
>>> def u10(n):
... if abs(n) < 10 or int(n) != n: return n
... s = str(n)
... m = s.rstrip('0')
... if len(m) == len(s): return n
... return Mul(int(m), Pow(10, len(s) - len(m), evaluate=0), evaluate=0)
...
>>> u10(12300)
123*10**2
>>> latex(Mul(_,1/x,evaluate=False))
'\\frac{123 \\cdot 10^{2}}{x}'�

Mathematical Function in Python does not work properly?

def trapezoidal(f, a, b, n):
h = float(b - a) / n
s = 0.0
s = s + f(a)
i=1
while i<=n-1:
s = s + f(a + i*h)
i= i +1
s = s + f(b)
s = s*h
return s
def f(x):
x = float(x)
return (-1/6)*(x-1)*(x-2)*(x+2)*(x-4)
lel = trapezoidal(f, -2, 4, 10)
print ("%.3f" % lel)
ok = f(-0.8)
print ok
I am trying to build a program that calculates integrals using the trapezoid rule. When I do it on paper it works fine but my f function does not work properly. For example f(-0.8) should be equal to 4.8384 but when I run it shows 29.0304. Please help?
If you are using Python 2.x
def f(x):
x = float(x)
return (-1/6)*(x-1)*(x-2)*(x+2)*(x-4)
The first term in your expression is doing integer division. The result of that division will be promoted to float later during the multiplication, but it is too late by then.
>>> (-1/6)
-1
You need to keep everything in floats
def f(x):
x = float(x)
return (-1.0/6.0)*(x-1)*(x-2)*(x+2)*(x-4)
Try
return (-1.0/6)*(x-1)*(x-2)*(x+2)*(x-4)

Pythagorean triplets in Python

I would like help in solving the following problem:
Find the product of the triplet of a,b,c for which:
a+b+c = 1000
and a^2+b^2=c^2.
I have written some python code, but it doesn't output anything. Please could you tell me what is wrong with it?
for a in range(1000):
for b in range(1000-a):
c = 1000-a-b
if a**2 + b**2 == c**2:
print a*b*c
else:
break
Your idea is correct. You have to fix your formatting and remove this break statement at the end ( this break makes you end the loop on first try. Oh and one more thing. a and b cant be 0 because it would be trivial otherwise (500**2+0**2==500**2).
def find_product(sum):
for a in range(1, sum):
for b in range(1, sum - a):
c = sum - a - b
if a**2 + b**2 == c**2:
print a*b*c
return a*b*c
else:
pass
#Keep looking! Dont end here :)
print 'No such triplet exists!'
So the result is:
>>> find_product(1000) # 200**2 + 375**2 = 425**2
31875000
Of course your code can be optimized by using some clever mathematical tricks :)

Fermat Factorisation with Python

New to Python and not sure why my fermat factorisation method is failing? I think it may have something to do with the way large numbers are being implemented but I don't know enough about the language to determine where I'm going wrong.
The code below works when n=p*q is made with p and q extremely close (as in within about 20 of each other) but seems to run forever if they are further apart. For example, with n=991*997 the code works correctly and executes in <1s, likewise for n=104729*104659. If I change it ton=103591*104659 however, it just runs forever (well, I let it go 2 hours then stopped it).
Any points in the right direction would be greatly appreciated!
Code:
import math
def isqrt(n):
x = n
y = (x + n // x) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
n=103591*104729
a=isqrt(n) + 1
b2=a*a - n
b=isqrt(b2)
while b*b!=b2:
a=a+1
b2=b2+2*a+1
b=isqrt(b2)
p=a+b
q=a-b
print('a=',a,'\n')
print('b=',b,'\n')
print('p=',p,'\n')
print('q=',q,'\n')
print('pq=',p*q,'\n')
print('n=',n,'\n')
print('diff=',n-p*q,'\n')
I looked up the algorithm on Wikipedia and this works for me:
#from math import ceil
def isqrt(n):
x = n
y = (x + n // x) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
def fermat(n, verbose=True):
a = isqrt(n) # int(ceil(n**0.5))
b2 = a*a - n
b = isqrt(n) # int(b2**0.5)
count = 0
while b*b != b2:
if verbose:
print('Trying: a=%s b2=%s b=%s' % (a, b2, b))
a = a + 1
b2 = a*a - n
b = isqrt(b2) # int(b2**0.5)
count += 1
p=a+b
q=a-b
assert n == p * q
print('a=',a)
print('b=',b)
print('p=',p)
print('q=',q)
print('pq=',p*q)
return p, q
n=103591*104729
fermat(n)
I tried a couple test cases. This one is from the wikipedia page:
>>> fermat(5959)
Trying: a=78 b2=125 b=11
Trying: a=79 b2=282 b=16
a= 80
b= 21
p= 101
q= 59
pq= 5959
(101, 59)
This one is your sample case:
>>> fermat(103591*104729)
Trying: a=104159 b2=115442 b=339
a= 104160
b= 569
p= 104729
q= 103591
pq= 10848981839
(104729, 103591)
Looking at the lines labeled "Trying" shows that, in both cases, it converges quite quickly.
UPDATE: Your very long integer from the comments factors as follows:
n_long=316033277426326097045474758505704980910037958719395560565571239100878192955228495343184968305477308460190076404967552110644822298179716669689426595435572597197633507818204621591917460417859294285475630901332588545477552125047019022149746524843545923758425353103063134585375275638257720039414711534847429265419
fermat(n_long, verbose=False)
a= 17777324810733646969488445787976391269105128850805128551409042425916175469326288448917184096591563031034494377135896478412527365012246902424894591094668262
b= 157517855001095328119226302991766503492827415095855495279739107269808590287074235
p= 17777324810733646969488445787976391269105128850805128551409042425916175469483806303918279424710789334026260880628723893508382860291986009694703181381742497
q= 17777324810733646969488445787976391269105128850805128551409042425916175469168770593916088768472336728042727873643069063316671869732507795155086000807594027
pq= 316033277426326097045474758505704980910037958719395560565571239100878192955228495343184968305477308460190076404967552110644822298179716669689426595435572597197633507818204621591917460417859294285475630901332588545477552125047019022149746524843545923758425353103063134585375275638257720039414711534847429265419
The error was doing the addition after incremeting a so the new value was not the square of a.
This works as intended :
while b*b!=b2:
b2+=2*a+1
a=a+1
b=isqrt(b2)
for big numbers it should be faster than computing the square which has quite a greater number of digits.

Categories