How to count scattered points in Julia - geometry

I would like to count the scattered red points inside the circle.
my code is:
using PyPlot # Here I define the circle
k = 100
ϕ = range(0,stop=2*π,length=k)
c = cos.(ϕ)
d = sin.(ϕ)
# Here I defined the scattered points with the circle
function scatterpoints(x,y)
n = 1000
x = -n:n
x = x / n
y = rand(2*n+1)
scatter(-x, -y;c="red",s=1)
scatter(x, y;c="red", s=1)
plot(c,d)
end
scatterpoints(x,y)
My approach (pseudocode) would be something like this:
using LinearAlgebra
if norm < radius of circle then
amount of points in circle = amount of points in circle + 1
end
Unfortunately I am not sure how to implement this in Julia.

your pretty much here with your pseudocode
using LinearAlgebra
n = 1000
N = 2n+1
x = range(-1, 1, length=N)
y = rand(N)
center = (0,0)
radius = 1
n_in_circle = 0
for i in 1:N
if norm((x[i], y[i]) .- center) < radius
n_in_circle += 1
end
end
println(n_in_circle) # 1565
println(pi*N/4) # 1571.581724958294

Related

Solving cars moving in multiple lanes simulation problem

I am trying to simulate cars moving in multiple lanes in python. The problem is like this:
The number of cars, the roadlength, the probability and vmax are all input values.
Rules:
1. If vi < vmax, increase the velocity vi of car i by one unit, that is, vi → vi + 1. This change models the process of acceleration to the maximum velocity.
2. Compute the distance to the next car in the same lane and the distance to the cars in both (if there are 2) lanes next to the car.
If d=max([d1,d2,d3]) and vi ≥ d, then reduce the velocity to vi = d − 1 to prevent crashes and switch lane to the lane where the distance to the next car is d (if there are multiple choose one at random or whichever you want).
Else (meaning there is at least one lane next to the car's lane or it could be the same lane that the car is in where d > vi) go in that lane and don't change the velocity of the car if there is more than one lane, pick one at random.
3. With probability p, reduce the velocity of a moving car by one unit: vi → vi − 1, only do this when v > 0 to avoid negative velocities
4. Update the position xi of car i so that xi(t + 1) = xi(t) + vi
Also the path of the cars is circular, meaning there will be cars in front and behind.
Below is my attempt to solve the problem. Don't get confused over the variables theta and r. theta is just the position and r is the lane.
My attempt:
from matplotlib import pyplot as plt
import random
import math
from matplotlib import animation
import numpy as np
from operator import attrgetter
roadLength = 100
numFrames = 200
nlanes = 3
numCars = 20
posss =[]
theta = []
r = []
color = []
probability = 0.5
vmax = 1
cars=[]
class Car:
def __init__(self, position, velocity, lane):
self.position = position
self.velocity = velocity
self.lane = lane
def pos(car,k):
rand = random.uniform(0,1)
if car[k].velocity < vmax:
car[k].velocity += 1
dist = 0
if car[k].lane == 1:
temp_lanes_between = [0,1]
if car[k].lane == nlanes and nlanes != 1:
temp_lanes_between = [-1 ,0]
if 1 < car[k].lane < nlanes:
temp_lanes_between = [-1 ,0, 1]
iterator = []
for p in range(k+1, numCars):
iterator.append(p)
#if car[k+1].position - car[k].position <= car[k].velocity and car[k].lane == car[k+1].lane:
for p in range(k):
iterator.append(p)
for s in iterator:
if car[s].lane - car[k].lane in temp_lanes_between:
temp_lanes_between.remove(car[s].lane - car[k].lane)
distance = min([abs((car[s].position - car[k].position) % roadLength), roadLength - abs((car[s].position - car[k].position) % roadLength)])
if dist < distance:
dist = distance
l = car[s].lane
if dist <= car[k].velocity:
break
if temp_lanes_between:
j=random.randrange(0, len(temp_lanes_between))
car[k].lane += temp_lanes_between[j]
if temp_lanes_between == [] and dist <= car[k].velocity:
car[k].velocity = dist - 1
car[k].lane = l
if rand < probability and car[k].velocity > 0:
car[k].velocity = car[k].velocity - 1
car[k].position = car[k].position + car[k].velocity
return car[k].position
for i in range(numCars):
cars.append(Car(i, 0, 1))
theta.append(0)
r.append(1)
color.append(i)
posss.append(i)
fig = plt.figure()
ax = fig.add_subplot(111)
point, = ax.plot(posss, r, 'o')
ax.set_xlim(-10, 1.2*numFrames)
ax.set_ylim(-2, nlanes + 3)
def animate(frameNr):
sort_cars = sorted(cars, key=attrgetter("position"))
for i in range(numCars):
pos(sort_cars,i)
for k in range(numCars):
theta[k]=cars[k].position
r[k]=cars[k].lane
print(theta)
print(r)
point.set_data(theta, r)
return point,
def simulate():
anim = animation.FuncAnimation(fig, animate,
frames=numFrames, interval=100, blit=True, repeat=False)
plt.show()
simulate()
I get error saying: "local variable 'l' referenced before assignment" in the line where car[k].lane = l . I know that they mean that l doesn't have any value and therefore I get this error. But I don't see how this is possible. Every time pos() is run it should always go through the line l = car[s].lane and there it gets assigned a value. Maybe there are more errors in the code above but I have really given it my best shot and I don't know what to do.
Thanks in advance!

Sphere-Sphere Intersection

I have two spheres that are intersecting, and I'm trying to find the intersection point nearest in the direction of the point (0,0,1)
My first sphere's (c1) center is at (c1x = 0, c1y = 0, c1z = 0) and has a radius of r1 = 2.0
My second sphere's (c2) center is at (c2x = 2, c2y = 0, c2z = 0) and has a radius of r2 = 2.0
I've been following the logic on this identical question for the 'Typical intersections' part, but was having some trouble understanding it and was hoping someone could help me.
First I'm finding the center of intersection c_i and radius of the intersecting circle r_i:
Here the first sphere has center c_1 and radius r_1, the second c_2 and r_2, and their intersection has center c_i and radius r_i. Let d = ||c_2 - c_1||, the distance between the spheres.
So sphere1 has center c_1 = (0,0,0) with r_1 = 2. Sphere2 has c_2 = (2,0,0) with r_2 = 2.0.
d = ||c_2 - c_1|| = 2
h = 1/2 + (r_1^2 - r_2^2)/(2* d^2)
So now I solve the function of h like so and get 0.5:
h = .5 + (2^2 - 2^2)/(2*2^2)
h = .5 + (0)/(8)
h = 0.5
We can sub this into our formula for c_i above to find the center of the circle of intersections.
c_i = c_1 + h * (c_2 - c_1)
(this equation was my original question, but a comment on this post helped me understand to solve it for each x,y,z)
c_i_x = c_1_x + h * (c_2_x - c_1_x)
c_i_x = 0 + 0.5 * (2 - 0) = 0.5 * 2
1 = c_i_x
c_i_y = c_1_y + h * (c_2_y - c_1_y)
c_i_y = 0 + 0.5 * (0- 0)
0 = c_i_y
c_i_z = c_1_z + h * (c_2_z - c_1_z)
c_i_z = 0 + 0.5 * (0 - 0)
0 = c_i_z
c_i = (c_i_x, c_i_z, c_i_z) = (1, 0, 0)
Then, reversing one of our earlier Pythagorean relations to find r_i:
r_i = sqrt(r_1*r_1 - hhd*d)
r_i = sqrt(4 - .5*.5*2*2)
r_i = sqrt(4 - 1)
r_i = sqrt(3)
r_i = 1.73205081
So if my calculations are correct, I know the circle where my two spheres intersect is centered at (1, 0, 0) and has a radius of 1.73205081
I feel somewhat confident about all the calculations above, the steps make sense as long as I didn't make any math mistakes. I know I'm getting closer but my understanding begins to weaken starting at this point. My end goal is to find an intersection point nearest to (0,0,1), and I have the circle of intersection, so I think what I need to do is find a point on that circle which is nearest to (0,0,1) right?
The next step from this solutionsays:
So, now we have the center and radius of our intersection. Now we can revolve this around the separating axis to get our full circle of solutions. The circle lies in a plane perpendicular to the separating axis, so we can take n_i = (c_2 - c_1)/d as the normal of this plane.
So finding the normal of the plane involves n_i = (c_2 - c_1)/d, do I need to do something similar for finding n_i for x, y, and z again?
n_i_x = (c_2_x - c_1_x)/d = (2-0)/2 = 2/2 = 1
n_i_y = (c_2_y - c_1_y)/d = (0-0)/2 = 0/2 = 0
n_i_z = (c_2_z - c_1_z)/d = (0-0)/2 = 0/2 = 0
After choosing a tangent and bitangent t_i and b_i perpendicular to this normal and each other, you can write any point on this circle as: p_i(theta) = c_i + r_i * (t_i * cos(theta) + b_i sin(theta));
Could I choose t_i and b_i from the point I want to be nearest to? (0,0,1)
Because of the Hairy Ball Theorem, there's no one universal way to choose the tangent/bitangent to use. My recommendation would be to pick one of the coordinate axes not parallel to n_i, and set t_i = normalize(cross(axis, n_i)), and b_i = cross(t_i, n_i) or somesuch.
c_i = c_1 + h * (c_2 - c_1)
This is vector expression, you have to write similar one for every component like this:
c_i.x = c_1.x + h * (c_2.x - c_1.x)
and similar for y and z
As a result, you'll get circle center coordinates:
c_i = (1, 0, 0)
As your citate says, choose axis not parallel to n vect0r- for example, y-axis, get it's direction vector Y_dir=(0,1,0) and multiply by n
t = Y_dir x n = (0, 0, 1)
b = n x t = (0, 1, 0)
Now you have two vectors t,b in circle plane to build circumference points.

Python shapely: How to triangulate just the inner area of the shape

I wanna convert this shape to triangles mesh using shapely in order to be used later as a 3d surface in unity3d, but the result seems is not good, because the triangles mesh cover areas outside this shape.
def get_complex_shape(nb_points = 10):
nb_shifts = 2
nb_lines = 0
shift_parameter = 2
r = 1
xy = get_points(0, 0, r, nb_points)
xy = np.array(xy)
shifts_indices = np.random.randint(0, nb_points ,nb_shifts) # choose random points
if(nb_shifts > 0):
xy[shifts_indices] = get_shifted_points(shifts_indices, nb_points, r + shift_parameter, 0, 0)
xy = np.append(xy, [xy[0]], axis = 0) # close the circle
x = xy[:,0]
y = xy[:,1]
if(nb_lines < 1): # normal circles
tck, u = interpolate.splprep([x, y], s=0)
unew = np.arange(0, 1.01, 0.01) # from 0 to 1.01 with step 0.01 [the number of points]
out = interpolate.splev(unew, tck) # a circle of 101 points
out = np.array(out).T
else: # lines and curves
out = new_add_random_lines(xy, nb_lines)
return out
enter code here
data = get_complex_shape(8)
points = MultiPoint(data)
union_points = cascaded_union(points)
triangles = triangulate(union_points)
This link is for the picture:
the blue picture is the polygon that I want to convert it to mesh of triangles, the right picture is the mesh of triangles which cover more than the inner area of the polygon. How could I cover just the inner area of the polygon?

ValueError: operands could not be broadcast together with shapes (3,) (0,)

My aim is to make the image1 move along the ring from its current position upto 180 degree. I have been trying to do different things but nothing seem to work. My final aim is to move both the images along the ring in different directions and finally merge them to and make them disappear.I keep getting the error above.Can you please help? Also can you tell how I can go about this problem?
from visual import *
import numpy as np
x = 3
y = 0
z = 0
i = pi/3
c = 0.120239 # A.U/minute
r = 1
for theta in arange(0, 2*pi, 0.1): #range of theta values; 0 to
xunit = r * sin(theta)*cos(i) +x
yunit = r * sin(theta)*sin(i) +y
zunit = r*cos(theta) +z
ring = curve( color = color.white ) #creates a curve
for theta in arange(0, 2*pi, 0.01):
ring.append( pos=(sin(theta)*cos(i) +x,sin(theta)*sin(i) +y,cos(theta) +z) )
image1=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
image2=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
earth=sphere(pos=(-3,0,-0.4),color=color.yellow, radius =0.3,material=materials.earth) #creates the observer
d_c_p = pow((x-xunit)**2 + (y-yunit)**2 + (z-zunit)**2,0.5) #calculates the distance between the center and points on ring
d_n_p = abs(yunit + 0.4998112152755791) #calculates the distance to the nearest point
t1 = ( d_c_p+d_n_p)/c
t0=d_c_p/c
t=t1-t0 #calculates the time it takes from one point to another
theta = []
t = []
dtheta = np.diff(theta) #calculates the difference in theta
dt = np.diff(t) #calculates the difference in t
speed = r*dtheta/dt #hence this calculates the speed
deltat = 0.005
t2=0
while True:
rate(5)
image2.pos = image2.pos + speed*deltat #increments the position of the image1
t2 = t2 + deltat
Your problem is that image2.pos is a vector (that's the "3" in the error message) but speed*deltat is a scalar (that's the "0" in the error message). You can't add a vector and a scalar. Instead of a scalar "speed" you need a vector velocity. There seem to be some errors in indentation in the program you posted, so there is some possibility I've misinterpreted what you're trying to do.
For VPython questions it's better to post to the VPython forum, where there are many more VPython users who will see your question than if you post to stackoverflow:
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

I want to create a 90 degree curve

I have gotten as far as making a set of rays, but I need to connect them. Any help? My code is as follows
from math import *
from graphics import *
i = 1
segments = 15
lastPoint = Point(100,0)
print("Begin")
win = GraphWin("Trigonometry", 1500, 1500)
while i<=segments:
angle =i*pi/segments
y = int(sin(angle)*100)
x = int(cos(angle)*100)
i = i+1
p = Point(x,y)
l = Line(p, lastPoint)
l.draw(win)
print(p.x, p.y)
print("End")
OP code draws only "rays" because, while point p lays on the circle, lastPoint doesn't change between iterations.
We have to update the value of lastPoint to literally the last point calculated in order to draw the arc as a series of consecutive segments.
Here is a modified code, with further explanations as asked by OP in his comment:
from math import *
from graphics import *
# Function to calculate the integer coordinates of a Point on a circle
# given the center (c, a Point), the radius (r) and the angle (a, radians)
def point_on_circle( c, r, a ) :
return Point( int(round(c.x + r*cos(a))), int(round(c.y + r*sin(a))) )
# Define the graphical output window, I'll set the coordinates system so
# that the origin is the bottom left corner of the windows, y axis is going
# upwards and 1 unit corresponds to 1 pixel
win = GraphWin("Trigonometry", 800, 600)
win.setCoords(0,0,800,600)
# Arc data. Angles are in degrees (more user friendly, but later will be
# transformed in radians for calculations), 0 is East, positive values
# are counterclockwise. A value of 360 for angle_range_deg gives a complete
# circle (polygon).
angle_start_deg = 0
angle_range_deg = 90
center = Point(10,10)
radius = 200
segments = 16
angle_start = radians(angle_start_deg)
angle_step = radians(angle_range_deg) / segments
# Initialize lastPoint with the position corresponding to angle_start
# (or i = 0). Try different values of all the previous variables
lastPoint = point_on_circle(center, radius, angle_start)
print("Begin")
i = 1
while i <= segments :
# update the angle to calculate a new point on the circle
angle = angle_start + i * angle_step
p = point_on_circle(center, radius, angle)
# draw a line between the last two points
l = Line(p, lastPoint)
l.draw(win)
print(p.x, p.y)
# update the variables to move on to the next segment which share an edge
# (the last point) with the previous segment
i = i + 1
lastPoint = p
print("End")

Resources