Making a table in Python 3(beginner) - python

So I just started learning Python 3 in school, and we had to make a function that
takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of a computed with the first function;
the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.
def mysqrt(a):
for x in range(1,int(1./2*a)):
while True:
y = (x + a/x) / 2
if y == x:
break
x = y
print(x)
print(mysqrt(16))

If you're allowed to use libraries
from tabulate import tabulate
from math import sqrt
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))
Outputs
num mysqrt sqrt
----- -------- -------
10 3.16228 3.16228
11 3.31662 3.31662
12 3.4641 3.4641
13 3.60555 3.60555
14 3.74166 3.74166
15 3.87298 3.87298
16 4 4
17 4.12311 4.12311
18 4.24264 4.24264
19 4.3589 4.3589
Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data

def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]

Related

I am wondering why the following outputs (529, 23) rather than (484, 22)

for x in range(0,501):
m = x ** 2
if m > 500:
break
print (m,x)
#this outputs a value for the highest square that is above 500 when I want the highest that is below 500
Your code assigns the value of m before breaking, so it stores that value before breaking.
Try this instead:
for x in range(0, 501):
if (x + 1) ** 2 > 500:
m = x ** 2
break
print(x, m)
Notes
Since you're new and it sounds like you're still learning about coding, I will add a few pointers.
First, you don't need to assign value to x to test the value of a function applied to it. Second, a better approach would be to use a while loop rather than a for loop, like this:
x = 0
while (x + 1) ** 2 < 500:
x = x + 1
print(x, x**2)
Additionally, loops are slow, brute force ways to write code. Sometimes that's okay or necessary, but when there's a very efficient way to solve a problem without a loop, it's usually better to use it. For example, to find the smallest integer whose square is less than or equal to x, we can use:
import math
def int_root(x):
return int(math.sqrt(x))
int_root(500)
The problem is you are breaking the loop once the value for m has already exceeded 500. So when you try to print the value for m it is the value that is above 500.
A solution would be to use the value of x and because we know that the desired value would be one less than this, we can compute m like so:
for x in range(501):
m = x ** 2
if m > 500:
break
x -= 1
print(x**2, x)
Yet another approach:
n = 0
for x in range(500):
m, n = n, (x + 1) ** 2
if n > 500:
break
print(m, x) # 484 22
As mentioned by others the issue with your code is that when you check to see if m is greater than 500, if m is exceeding 500 the program breaks the loop, the catch is that m has already been given the value that is over 500 and as such prints that out instead of the desired one before. To counteract this we can add to x and square the result to see if that answer is over 500 and if it is the program will break.
def squareless(top):
for x in range(0, top):
if (x + 1) ** 2 > top + 1:
m = x ** 2
print(x, m)
break
squareless(500)
You break the loop after m already exceeds 500, so (529, 23) is expected. Note that 23 ** 2 = 529. You want to retreat to the previous x and previous m in this case.
for x in range(0,501):
m = x ** 2
if m > 500:
x -= 1
m = x ** 2
break
print (m,x) # 484 22
Or check the next x to break before exceeding 500:
for x in range(0,501):
m = x ** 2
if (x+1) ** 2 > 500:
break

More information on output array with equation and indicies

I have a math function whose output is defined by two variables, x and y.
The function is e^(x^3 + y^2).
I want to calculate every possible integer combination between 1 and some defined integer for x and y, and place them in an array so that each output is aligned with the cooresponding x value and y value index. So something like:
given:
x = 3
y = 5
output would be an array like this:
f(1,1) f(1,2) f(1,3)
f(2,1) f(2,2) f(2,3)
f(3,1) f(3,2) f(3,3)
f(4,1) f(4,2) f(4,3)
f(5,1) f(5,2) f(5,3)
I feel like this is an easy problem to tackle but I have limited knowledge. The code that follows is the best description.
import math
import numpy as np
equation = math.exp(x**3 + y**2)
#start at 1, not zero
i = 1
j = 1
#i want an array output
output = []
#function
def shape_f (i,j):
shape = []
output.append(shape)
while i < x + 1:
while j < y +1:
return math.exp(i**3 + j**2)
#increase counter
i = i +1
j = j +1
print output
I've gotten a blank array recently but I have also gotten one value (int instead of an array)
I am not sure if you have an indentation error, but it looks like you never do anything with the output of the function shape_f. You should define your equation as a function, rather than expression assignment. Then you can make a function that populates a list of lists as you describes.
import math
def equation(x, y):
return math.exp(x**3 + y**2)
def make_matrix(x_max, y_max, x_min=1, y_min=1):
out = []
for i in range(x_min, x_max+1):
row = []
for j in range(y_min, y_max+1):
row.append(equation(i, j))
out.append(row)
return out
matrix = make_matrix(3, 3)
matrix
# returns:
[[7.38905609893065, 148.4131591025766, 22026.465794806718],
[8103.083927575384, 162754.79141900392, 24154952.7535753],
[1446257064291.475, 29048849665247.426, 4311231547115195.0]]
We can do this very simply with numpy.
First, we use np.arange to generate a range of values from 0 (to simplify indexing) to a maximum value for both x and y. We can perform exponentiation, in a vectorised manner, to get the values of x^3 and y^2.
Next, we can apply np.add on the outer product of x^3 and y^3 to get every possible combination thereof. The final step is taking the natural exponential of the result:
x_max = 3
y_max = 5
x = np.arange(x_max + 1) ** 3
y = np.arange(y_max + 1) ** 2
result = np.e ** np.add.outer(x, y)
print(result[2, 3]) # e^(2 ** 3 + 3 ** 2)
Output:
24154952.753575277
A trivial solution would be to use the broadcasting feature of numpy with the exp function:
x = 3
y = 5
i = np.arange(y).reshape(-1, 1) + 1
j = np.arange(x).reshape(1, -1) + 1
result = np.exp(j**3 + y**2)
The reshape operations make i into a column with y elements and j into a row with x elements. Exponentiation does not change those shapes. Broadcasting happens when you add the two arrays together. The unit dimensions in one array get expanded to the corresponding dimension in the other. The result is a y-by-x matrix.

How to do numerical integration in python?

I can't install anything new I need to use the default python library and I have to integrate a function. I can get the value for any f(x) and I need to integrate from 0 to 6 for my function f(x).
In discrete form, integration is just summation, i.e.
where n is the number of samples. If we let b-a/n be dx (the 'width' of our sample) then we can write this in python as such:
def integrate(f, a, b, dx=0.1):
i = a
s = 0
while i <= b:
s += f(i)*dx
i += dx
return s
Note that we make use of higher-order functions here. Specifically, f is a function that is passed to integrate. a, b are our bounds and dx is 1/10 by default. This allows us to apply our new integration function to any function we wish, like so:
# the linear function, y = x
def linear(x):
return x
integrate(linear, 1, 6) // output: 17.85
# or using lamdba function we can write it directly in the argument
# here is the quadratic function, y=x^2
integrate(lambda x: x**2, 0, 10) // output: 338.35
You can use quadpy (out of my zoo of packages):
import numpy
import quadpy
def f(x):
return numpy.sin(x) - x
val, err = quadpy.quad(f, 0.0, 6.0)
print(val)
-17.96017028290743
def func():
print "F(x) = 2x + 3"
x = int(raw_input('Enter an integer value for x: '))
Fx = 2 * x + 3
return Fx
print func()
using the input function in python, you can randomly enter any number you want and get the function or if hard coding this this necessary you can use a for loop and append the numbers to a list for example
def func2():
print "F(x) = 2x + 3"
x = []
for numbers in range(1,7):
x.append(numbers)
upd = 0
for i in x:
Fx = 2 * x[upd] + 3
upd +=1
print Fx
print func2()
EDIT: if you would like the numbers to start counting from 0 set the first value in range to 0 instead of 1

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.

Adding two given floating point numbers in Python?

How would I create a method with Python to add floating point numbers that are in a list, without using libraries?. The teacher gave us this code, and I didn't understand it, could anyone else give me another example?
def msum(iterable):
"Full precision summation using multiple floats for intermediate values"
partials = [] # sorted, non-overlapping partial sums
for x in iterable:
i = 0
for y in partials:
if abs(x) < abs(y):
x, y = y, x
hi = x + y
lo = y - (hi - x)
if lo:
partials[i] = lo
i += 1
x = hi
partials[i:] = [x]
return sum(partials, 0.0)
A version of the Kahan algorithm in python would look like this:
def msum(input):
sum = 0.0
c = 0.0
for x in input:
y = x - c
t = sum + y
c = (t - sum) - y
sum = t
return sum
And what does "without using other libraries" even mean? Of course you could just have
def msum(input):
return sum(input)

Categories