Making an Euclidean Distance Matrix with Random Points in Python - python

I wrote a code that produces the desired number of points in a certain width and length range in the coordinate system. How can I calculate and tabulate the distance matrix of these points I produced using the Euclidean method?
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
Output is:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76)
Process finished with exit code 0
How can I create a distance matrix with rondom points like this example:
Thanks a lot for the help.

If you want to use external modules, scipy is very efficient for matrix calculations.
import random
import pandas as pd
from scipy.spatial import distance
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)
Output
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
0 1 2 3
0 0.000000 0.584322 0.985072 5.856736
1 0.584322 0.000000 0.669935 6.277323
2 0.985072 0.669935 0.000000 6.839240
3 5.856736 6.277323 6.839240 0.000000

Related

How to find/calculate the shaded area of this shape in python?

I'm trying to write a python program to calculate the shaded area of the circle in this picture:
[![enter image description here][1]][1]
Here is the input and output:
Enter the radius of a circle: 10
Enter the side of square :3
Enter the width of a rectangle :4
Enter the length of a rectangle :2
The shaded area is : 12.0
Here is my code:
PI = 3.14
radius = float(input("Enter the radius of a circle:"))
area = PI * radius ** 2
side = int(input("Enter the side of square:"))
area = side*side
width = float(input("Enter the width of a rectangle:"))
length = float(input("Enter the length of a rectangle:"))
area = width * length
perimeter = (width + length) * 2
print("The shaded area is :", perimeter)
Problem
You are overwriting the value of area and the previous assigned values are lost.
Example
area = input('enter first value')
10
# the value of area is 10
area = input('enter second value')
3
# the value of area is now 3 and 10 is lost
However you can use area -= number or area += number to substract or add a number to the current value of the variable like so:
area = input('enter first value')
10
# the value of area is 10
area -= input('enter second value')
3
# the value of area is now 10 - 3 = 7
As correctly pointed out in the comments you should also import math and use math.pi instead of using the value 3.14
The correct output for the shaded area is:
Enter the radius of a circle:10
Enter the side of square:3
Enter the width of a rectangle:4
Enter the length of a rectangle:2
The shaded area is : 297.1592653589793
>
I would recommend solution 1 as variables should have meaningful names (unlike solution 2):
Meaningful Variable Names
and solution 3 is a bit harder to read and understand:
Make your code easy to read/understand
Solution 1 (Using different variable names)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
circle_area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
square_area = side * side
# but you could use square_area = side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
rectangle_area = width * length
shaded_area = circle_area - square_area - rectangle_area
print("The shaded area is :", shaded_area)
findDimensions()
Solution 2 (Updating the area variable instead of overwriting it)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
area -= side * side
# but you could use area -= side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
area -= width * length
print("The shaded area is :", area)
findDimensions()
Solution 3 (Moving calculations to the end)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
side = int(input("Enter the side of square:"))
# side = 3
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
shaded_area = (math.pi * radius ** 2) - (side * side) - (width * length)
print("The shaded area is :", shaded_area)
findDimensions()

math.sin() not returning proper value

Hello I have an equation I am trying to calculate using python. Where
The desired output I am looking for is 1.71528
Below I have my current code with all of the current values d should equal 100 and theta should equal 60.
import math
m = 0.065
g = 9.8
print("Input the distance to professor")
d = 100 # float(input())
k = 25
print("Now input the value for theta")
theta = 60 # float(input())
x = math.sqrt(m*g*d/k*math.sin(2 * theta))
print(x, 'meters')
The output I get when I run this code is 1.2163047715819324 meters
I think my issue is something with math.sin any help would be appreciated thanks.
Convert to theta to radians and put brackets around the denominator.
x = math.sqrt(m*g*d/(k*math.sin(2 * math.radians(theta))))
print(f"{x:.5f} meters")
Will result in
Input the distance to professor
100
Now input the value for theta
60
1.71528 meters

Trying to figure out how to find the final distance on my turtle with random number

This is my code, I'm trying to figure out how to get the total distance of the entire length that my turtle has traveled and I don't know how to figure it without taking it out of a loop which I can't do because the numsteps is an input. This is for school by the way
for a in range(numsteps):
s = randint(-100,100)
angle = random() * 2 * pi
x = s * cos(angle)
y = s * sin(angle)
walking.goto(x,y)
distance = sqrt(x ** 2 + y ** 2)
finald.goto(x,y)
print("The final distance is {:,.0f}".format(distance))
print("Your total distance traveled is {}")
You have to save your previous position to compute the distance from the current position to it.
Then every time after computing the distance (near the end of the loop) the current position becomes a previous one:
from math import sin, cos, pi, sqrt
from random import random, randint
start_x, start_y = 0, 0 # The starting point coordinates
previous_x, previous_y = start_x, start_y
total_distance = 0 # We will progressively increase it
numsteps = int(input("Number of steps: "))
for __ in range(numsteps):
s = randint(-100, 100)
angle = random() * 2 * pi
x = s * cos(angle)
y = s * sin(angle)
# walking.goto(x, y) # I commented it out for testing
distance = sqrt((x - previous_x) ** 2 + (y - previous_y) ** 2)
total_distance += distance
prev_x, prev_y = x, y
final_distance = sqrt((x - start_x) ** 2 + (y - start_y) ** 2)
print("The final distance is {:,.0f}".format(final_distance))
print("Your total distance traveled is {:,.0f}".format(total_distance))
Note the __ instead of your a (or other regular name) — this special name (one or two underscore characters) indicates that its value is out of our interest.
(Because we use range(numsteps) only as a counter.)
I'd make simplifications based on some observations:
Turtle already knows the distance function, no need to reinvent it
Moving backwards (negative distance) when we can head in any direction is redundant -- it's really no different than moving forward in any direction.
We can more easily calculate how far we did move than measure how far we will move.
This results in code more like:
from math import pi
from random import random
from turtle import Screen, Turtle
numsteps = int(input("Number of steps: "))
screen = Screen()
walking = Turtle()
walking.radians()
total_distance = 0 # sum of all distances traveled
for _ in range(numsteps):
previous = walking.position()
angle = random() * 2 * pi
distance = random() * 100
walking.setheading(angle)
walking.forward(distance)
total_distance += walking.distance(previous)
final_distance = walking.distance(0, 0) # distance from where we started
print("Your final distance traveled is {:,.0f} pixels".format(final_distance))
print("Your total distance traveled is {:,.0f} pixels".format(total_distance))
screen.exitonclick()
OUTPUT
> python3 test.py
Number of steps: 100
Your final distance traveled is 356 pixels
Your total distance traveled is 4,630 pixels
>

Determining final velocity at a target distance

In this program I've been working on with Python the goal is to take user inputs on a given initial velocity, angle, and how far away a structure is/how tall it is we're aiming for. I have been able to calculate how long it takes for something to reach a target, but I'm not sure why the final velocity (how fast it is going when it reaches the target) is coming up wrong.
# User inputs
velocity = float(input('Give me a velocity to fire at (in m/s): '))
angle = float(input('Give me an angle to fire at: '))
distance = float(input('Give me how far away you are from the
structure: '))
height = float(input('Give me the height of the structure (in meters):
'))
slingshot = 5 #Height of slingshot in meters
gravity = 9.8 #Earth gravity
# Converting angles to radians
angleRad = math.radians(angle)
# Computing our x and y coordinate
x = math.cos(angleRad)
y = math.sin(angleRad)
# Calculations
time = distance/(velocity * x)
vx = x
vy = y + (-9.8 * time)
finalVelocity = math.sqrt((vx ** 2) + (vy ** 2))
# Output of program
print('It takes your bird' , time , 'seconds to reach the structure')
print('Your velocity at the target distance is' , finalVelocity ,
'meters per second.')
Here is a sample input and what the expected output should be:
Input Velocity: 20
Input Angle: 40
Input Distance: 25
Input Height of Structure: 15
Expected Output:
Time to reach structure: 1.63176 s
Final velocity: 15.6384 s
My Program's Output:
Time to reach structure: 1.63176
Final velocity: 15.36755
At first glance it would appear my program is very close, so I suspected a rounding error, but it is mere coincidence with the chosen numbers that they're close.
You miscalculated the horizontal and vertical components of the final velocity. You only used the cosine and sine of the angle, rather than the (magnitude of the) initial velocity times the cosine and sine, respectively. If you modify the following two lines of code, you will obtain the result you were looking for given the sample input you provided:
vx = velocity * x
vy = velocity * y - 9.8 * time
I rewrote your original code a bit and also computed the final height to check whether the structure was hit or not, so feel free to use it if needed:
import math
# User inputs
# v0 = float(input('Give me a velocity to fire at (in m/s): '))
# angle = float(input('Give me an angle to fire at: '))
# distance = float(input('Give me how far away you are from the structure: '))
# height_structure = float(input('Give me the height of the structure (in meters):'))
# Test inputs
v0 = 20
angle = 40
distance = 25
height_structure = 15
# Constants
height_slingshot = 5 # Height of slingshot in meters
g = 9.8 # Earth gravity
# Converting angle to radians
angleRad = math.radians(angle)
# Computing initial velocity components
vx0 = v0 * math.cos(angleRad)
vy0 = v0 * math.sin(angleRad)
# Computing time to travel horizontal distance
t_x = distance / vx0
# Computing final vertical velocity component
vy_final = vy0 - g * t_x
# Computing magnitude of final velocity
v_final = math.sqrt((vx0 ** 2) + (vy_final ** 2))
# Note: Horizontal component is constant
# Computing final height
y_final = height_slingshot + vy0 * t_x - g / 2 * t_x ** 2
# Verify if t_x was computed correctly
# t_y1 = (vy0 + math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# t_y2 = (vy0 - math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# Output of program
print('It takes your bird', t_x, 'seconds to reach the structure.')
print('Your velocity at the target distance is', v_final,
'meters per second.')
print('\nFinal height: ', y_final)
print('Structure height:', height_structure)
if 0. <= y_final <= height_structure:
print('\nYou hit the structure!')
elif y_final < 0:
print('\nYou missed. Not far enough!')
else:
print('\nYou missed. Too far!')

Calculates the width of a rectangle given the area and perimeter

Ive based the e1 and e2 sections of code as two halves of the google equation found when asking calculate width of a rectangle given perimeter and area.
This section of code is set to be part of a larger piece that displays the calculated rectangle in a visual form instead of using integers, however when i test it, the answer it gives is incorrect.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = int(perim**2 - (16 * area))
e3 = int(math.sqrt(e2))
width = int(e1 * e3)
print(width)
It's recommended you name your variables better so we know what you're trying to calculate.
From the Google formula, you should just translate it directly.
import math
def get_width(P, A):
_sqrt = math.sqrt(P**2 - 16*A)
width_plus = 0.25*(P + _sqrt)
width_minus = 0.25*(P - _sqrt)
return width_minus, width_plus
print(get_width(16, 12)) # (2.0, 6.0)
print(get_width(100, 40)) # (0.8132267551043526, 49.18677324489565)
You get zero because int(0.8132267551043526) == 0
Important note: Your calcuation doesn't check
area <= (perim**2)/16
Here is the fixed code :
import math
print("Welcome to Rectangles! Please dont use decimals!")
S = int(input("Area "))
P = int(input("Perim "))
b = (math.sqrt (P**2-16*S)+P) /4
a = P/2-b
print (a,b)
If you don't need to use this equation specifically, it'd be easier to just brute force it.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
lengths = range(math.ceil(perim/4), perim/2)
for l in lengths:
if l*(perim/2 - l) == area:
print(l)
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = abs(perim**2 - (16 * area))
e3 = math.sqrt(e2)
width = e1 * e3
print(width)

Categories

Resources