How to output a list using a while loop? - python

Firstly, I have tried doing this code but have no success in outputting a list using a while loop.
I have done the suggestions of both #
Someone_who_likes_SE and #ace1234
The code I have is this:
import math
x1 = 0.1
x2 = 0.5
d = 0.2
theta = 1.14840969035
x_list = []
i = x1
while (i < x2):
i = i + d * math.cos(theta)
x_list.append(i)
print(x_list)
The output are:
[0.181987700205 0.263975400411 0.345963100616 0.427950800822 0.5099385010273055]
Is there a way to get the 0.1 at the start?
The 0.50999385010273055 should also not be there as it is over 0.5.

Change the while loop to -
while (i < x2):
i = i + d * math.cos(theta)
x_list.append(i)
print(x_list)
You want the list, so you should print the list. But what you have done is print i
Edit - If you want 0.1 in start and want to remove 0.50.... then move append method up like this -
while (i < x2):
x_list.append(i)
i = i + d * math.cos(theta)
print(x_list)

It's actually working.
Line 11 is actually appending to the list:
import math
x1 = 0.1
x2 = 0.5
d = 0.2
theta = 1.14840969035
x_list = []
i = x1
while (i < x2):
print(i)
i = i + d * math.cos(theta)
x_list.append(i) # <--- appending
only you're not printing it out.
import math
x1 = 0.1
x2 = 0.5
d = 0.2
theta = 1.14840969035
x_list = []
i = x1
while (i < x2):
print(i) # <--- prints out the numbers.
i = i + d * math.cos(theta)
x_list.append(i)
So this will work:
import math
x1 = 0.1
x2 = 0.5
d = 0.2
theta = 1.14840969035
x_list = []
i = x1
while (i < x2):
#print(i)
i = i + d * math.cos(theta)
x_list.append(i)
print(x_list)
Output:
[0.18198770020501776, 0.26397540041003553, 0.3459631006150533, 0.4279508008200711, 0.5099385010250889]

The output that you saw is the print that I commented below. If you print the list object after loop the result is that you're expecting.
import math
x1 = 0.1
x2 = 0.5
d = 0.2
theta = 1.14840969035
x_list = []
i = x1
while (i < x2):
#print(i) <--- this is that you was seing!
i = i + d * math.cos(theta)
x_list.append(i)
## try print the list object:
print(x_list)

Related

Gradient descent in matlab work but in python not work

Matlab version
For the contour plotting
[x1,x2\] = meshgrid(-30:0.5:30, -30:0.5:30);
F = (x1-2).^2 + 2\*(x2 - 3).^2;
figure;
surf(x1,x2,F);
hold on;
contour(x1,x2,F);
figure;
contour(x1,x2,F,20);
hold on;
For initialize the value of the matrix and vector
A = [1 0; 0 2];
AT = A';
b = [4; 12];
Nit = 100; % no of iteration of our GD
tol = 1e-5; % error tolerance
lr = 0.2; % learning rate
xk = [-20;-20\]; % initial x value
noIterations = 1;
gradErr = [];
The looping for the gradient descent
for k =1:Nit
x_old = xk;
xk = xk - lr*AT*(A*xk - b); % Main GD step
gradErr(k) = norm(AT*(A*xk-b),'fro');
if gradErr(k) < tol
break;
end
plot([x_old(1) xk(1)],[x_old(2) xk(2)],'ko-')
noIterations = noIterations + 1;
end
Python version
Contour plotting part
import numpy as np
import matplotlib.pyplot as plt
x1,x2 = np.meshgrid(np.arange(- 30,30+0.5,0.5),np.arange(- 30,30+0.5,0.5))
F = (x1 - 2) ** 2 + 2 * (x2 - 3) ** 2
fig=plt.figure()
surf=fig.gca(projection='3d')
surf.plot_surface(x1,x2,F)
surf.contour(x1,x2,F)
plt.show()
fig,surf=plt.subplots()
plt.contour(x1,x2,F,20)
plt.show()
Initialize the value of the matrix and vector
A = np.array([[1,0],[0,2]])
AT = np.transpose(A)
b = np.array([[4],[12]])
Nit = 100
tol = 1e-05
lr = 0.2
xk = np.array([[-10],[-10]])
noIterations = 1
gradErr = []
Main problem is here where the looping has the bug cause it cant run the coding
for k in range(Nit):
x_old = xk
xk = xk - lr*np.matmul(AT,np.matmul(A,xk - b))
gradErr[k] = np.linalg.norm(AT * (A * xk - b),'fro')
if gradErr[k] < tol:
break
plt.plot(np.array([x_old(1),xk(1)]),np.array([x_old(2),xk(2)]),'ko-')
noIterations = noIterations + 1
May I know what is the problem for my python version in the looping part cant work but in matlab version is work well?
To access k-th element of gradErr, it has to be pre-assign a positive length. In your case, it is initialized as an empty list, which is the cause of IndexError. A simple fix is to use gradErr=np.zeros(Nit) Full code after making proper modification is the following:
import numpy as np
import matplotlib.pyplot as plt
x1,x2 = np.meshgrid(np.arange(-30, 30+0.5, 0.5), np.arange(-30, 30+0.5, 0.5))
F = (x1 - 2) ** 2 + 2 * (x2 - 3) ** 2
fig=plt.figure()
surf = fig.add_subplot(1, 1, 1, projection='3d')
surf.plot_surface(x1,x2,F)
surf.contour(x1,x2,F)
plt.show()
fig, surf=plt.subplots()
plt.contour(x1, x2, F, 20)
plt.show()
A = np.array([[1,0], [0,2]])
AT = np.transpose(A)
b = np.array([[4], [12]])
Nit = 100
tol = 1e-05
lr = 0.2
xk = np.array([[-10], [-10]])
noIterations = 1
gradErr = np.zeros(Nit)
for k in range(Nit):
x_old = xk
xk = xk - lr * np.matmul(AT, np.matmul(A, xk - b))
gradErr[k] = np.linalg.norm(AT * (A * xk - b),'fro')
if gradErr[k] < tol:
break
plt.plot(np.array([x_old[0], xk[0]]),np.array([x_old[1], xk[1]]),'ko-')
noIterations = noIterations + 1

Fading a Line Exponentially

I'd like to fade the values of a line on the Y axis using a gradient that I can control.
This is a simplified version of what I'm trying right now.
y_values = [1,1,1,1,1,1]
for i, y in enumerate(y_values): #i is the index, y is the individual y value
perc = i/(len(y_values)-1) #progress the fade by the percentage of the index divided by the total values
amt = y * perc #y is the target amount to decrease multiplied by index percentage
y -= amt
print(i,y)
This code produces this:
1.0
0.8
0.6
0.4
0.2
0.0
It's creating a linear fade, but how do I increase the fade with an exponential fade like this?
Thank you!
To make exponential fading, you have to provide two coefficients to provide initial factor 1.0 at the start value x1 and desired final factor k at the end of interval x2
y = y * f(x)
f(x) = A * exp(-B * x)
So
f(x1) = 1 = A * exp(B * x1)
f(x2) = k = A * exp(B * x2)
divide the second by the first
k = exp(B * (x2 - x1))
ln(k) = B * (x2 - x1)
so
B = ln(k) / (x2 - x1)
A = exp(B * x1)
Example for x1 = 0, x2 = 60, k = 0.01
B = -4.6/60= -0.076
A = 1
f(x) = exp(-0.076*x)
f(30) = exp(-0.076*20) = 0.1
Python example:
import math
def calcfading(x1, x2, ratio):
B = math.log(ratio) / (x2 - x1)
A = math.exp(B * x1)
return A, B
def coef(x, fade):
return fade[0]*math.exp(x*fade[1])
cosine = [[x, math.cos(x)] for x in range(0, 11)]
print(cosine)
print()
fade = calcfading(0, 10, 0.01)
expcosine = [[s[0], coef(s[0], fade)*s[1]] for s in cosine]
print(expcosine)

How to turn this while loop into a for loop and output a list with float values? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am working on this Python code for my thesis. Let's say
x1 = 0.1
x2 = 0.5
y1 = 0.1
y2 = 0.99
d = 0.1
def Calculate():
tan_theta = ((y2-y1)/(x2-x1))
theta = math.atan(tan_theta)
i = x1
while (i < x2):
print(i)
i = i + d * math.cos(theta)
j = y1
while (j < y2):
print(j)
j = j + d * math.sin(theta)
Calculate()
The values outputted are correct as:
0.1
0.140993850103
...
0.1
0.191211316479
...
But I need them to be on a list such as:
[0.1 0.140993850103 ...]
[0.1 0.191211316479 ...]
I also needed the output to become a list and did some examples previously done such as Python while Loop output to List but it did not work for me.
result_list = []
i = x1
while (i < x2):
i = i + d * math.cos(theta)
result_list.append(i)
print(i)
result_list2 = []
j = y1
while (j < y2):
j = j + d * math.sin(theta)
result_list2.append(j)
print(j)
It was still outputting the same results as before and it even outputted values outside the range.
I also tried using a For Loop by using numpy since I am dealing with float values. I tried using:
import numpy as np
for i in [np.arange(x1, x2, x1 + d * math.cos(theta))]:
print(i)
for j in [np.arange(y1, y2, y1 + d * math.sin(theta))]:
print(j)
But the values I get are:
[0.1 0.24099385 0.3819877]
[0.1 0.29121132 0.48242263 0.67363395 0.86484527]
which are wrong.
I should also be getting the same amount of values (i.e. 3 'x' values and 3 'y' values and not 3 'x' and 5 'y'.
I'm not sure how to progress now as I have done everything I can think of.
I think the most Pythonic way to reach what you are looking for is just to create your own float_range to emulate the range, for example:
import math
x1 = 0.1
x2 = 0.5
y1 = 0.1
y2 = 0.99
d = 0.1
def float_range(beg, end, increment):
while beg < end:
yield beg
beg += increment
def Calculate():
tan_theta = (y2 - y1) / (x2 - x1)
theta = math.atan(tan_theta)
list_x = list(float_range(x1, x2, d * math.cos(theta)))
print(list_x)
list_y = list(float_range(y1, y2, d * math.sin(theta)))
print(list_y)
Calculate()
Also, you can use it in a for loop, like:
for x in float_range(y1, y2, d * math.sin(theta)):
print(x)

How to not print the j in Python complex numbers?

Let's say one of the answers is supposed to be 3.00, it will be printed as 3.00+0.00j.
How do I remove the j and have it as 3.00 only?
# Viete's Algorithm
def result_2(a3,a2,a0,a1):
b = b_cof(a3,a2,a1,a0)
a = a_cof(a3,a2,a1)
p = P(a3, a2)
r = -(b / 2.0)
q = (a / 3.0)
if ((r**2)+(q**3))<= 0.0:
if q==0:
theta = 0
if q<0:
theta = cmath.acos(r/(-q**(3.0/2.0)))
phi1 = theta / 3.0
phi2 = phi1 - ((2*cmath.pi) / 3.0)
phi3 = phi1 + ((2*cmath.pi) / 3.0)
print("X1 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi1)-p/3.0))
print("X2 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi2)-p/3.0))
print("X3 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi3)-p/3.0))
You could drop the imaginary part from the number if it is zero:
>>> x=3+0j
>>> print(f"X1 = {x if x.imag else x.real:.2f}")
X1 = 3.00
>>> x=3+1j
>>> print(f"X1 = {x if x.imag else x.real:.2f}")
X1 = 3.00+1.00j

Simplex Noise Function: Unexpected Results

I'm trying to adapt this noise module to a project I'm working on but I'm not getting the results I was expecting:
https://pypi.python.org/pypi/noise/
Instead of a varied height-map, each row tends to have the exact same value. If I create something 250x250 it will generate the same value 250 times and then generate a new value 250 times until it ends.
Here is the function I'm currently using. I understand this function fairly well but I'm just not sure how to get more "interesting" results. Thank you for your help.
class SimplexNoise(BaseNoise):
def noise2(self, x, y):
"""2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
"""
# Skew input space to determine which simplex (triangle) we are in
s = (x + y) * _F2
i = floor(x + s)
j = floor(y + s)
t = (i + j) * _G2
x0 = x - (i - t) # "Unskewed" distances from cell origin
y0 = y - (j - t)
if x0 > y0:
i1 = 1; j1 = 0 # Lower triangle, XY order: (0,0)->(1,0)->(1,1)
else:
i1 = 0; j1 = 1 # Upper triangle, YX order: (0,0)->(0,1)->(1,1)
x1 = x0 - i1 + _G2 # Offsets for middle corner in (x,y) unskewed coords
y1 = y0 - j1 + _G2
x2 = x0 + _G2 * 2.0 - 1.0 # Offsets for last corner in (x,y) unskewed coords
y2 = y0 + _G2 * 2.0 - 1.0
# Determine hashed gradient indices of the three simplex corners
perm = BaseNoise.permutation
ii = int(i) % BaseNoise.period
jj = int(j) % BaseNoise.period
gi0 = perm[ii + perm[jj]] % 12
gi1 = perm[ii + i1 + perm[jj + j1]] % 12
gi2 = perm[ii + 1 + perm[jj + 1]] % 12
# Calculate the contribution from the three corners
tt = 0.5 - x0**2 - y0**2
if tt > 0:
g = _GRAD3[gi0]
noise = tt**4 * (g[0] * x0 + g[1] * y0)
else:
noise = 0.0
tt = 0.5 - x1**2 - y1**2
if tt > 0:
g = _GRAD3[gi1]
noise += tt**4 * (g[0] * x1 + g[1] * y1)
tt = 0.5 - x2**2 - y2**2
if tt > 0:
g = _GRAD3[gi2]
noise += tt**4 * (g[0] * x2 + g[1] * y2)
return noise * 70.0 # scale noise to [-1, 1]
win = pygcurse.PygcurseWindow(85, 70, 'Generate')
octaves = 2
ysize = 150
xsize = 150
freq = 32.0 * octaves
for y in range(ysize):
for x in range(xsize):
tile = SimplexNoise.noise2(x / freq, y / freq, octaves)
win.write(str(tile) + "\n")

Categories

Resources