Is this Python script correct? - python

I have a Programming Assignment in my class and I tried my best to understand everything but I want to make sure that my script is correct before I submit it. I need to find the area of a triangle which is given by the formula:
Area = 1/2 * Base * Height
This is my answer:
# The base and height of this triangle are inches
base = 12.0
height = 16.0
# The area of a triangle is 1/2 * base * height
area = 1/2 * base * height
print (area)
Is my code correct?

Yes, this code is correct, by assigning the values to different variables it is clear what you have done.

Related

estimate object's height and width using lidar data

I'am currently working on lidar and camera fusion for object detection, distance and size estimation. I'am struggling with the width and height estimation using lidar data ( x and y coordinates ) .
i need help with a method that makes use of all the info extracted from the lidar sensor to estimate the object's size!
NB :1- the bbox are provided by the yolov5 algorithm.
2- I have calculated the actual distance of each object inside a bbox.
height and width of the cyclist in the image attached : enter image description here
This is geometry around the "pinhole camera" model.
Let's first regard the unit circle.
Picture from debraborkovitz.com
Your camera is at the origin looking at B. The object is the line BC. Let's say it is 1 meter away (O-B), and 0.5 meters tall (B-C). It spans a certain angle of the unit circle (your view). Let's call that alpha (or theta, doesn't matter).
tan(alpha) * 1.0 m = 0.5 m
tan(alpha) * distance[m] = length[m]
tan(alpha) = length[m] / distance[m]
alpha isn't important, but tan(alpha) is, because it's proportional to the object's length. Only keep that in mind.
Focal length is just a factor, describing image resolution. Say f = 1000 px, then this object would be 500 px tall because
length[px] = f[px] * tan(alpha)
= f[px] * length[m] / distance[m]
Now, if lidar says the object is 5 m away, and the image says the object is 300 px tall/wide, you calculate
length[px] = f[px] * length[m] / distance[m]
rearrange
length[m] = length[px] / f[px] * distance[m]
length[m] = 300px / 1000px * 5m
length[m] = 1.5 m
You need to know the focal length (in pixels) for your camera. That is either given by the manufacturer, somewhere in the documentation, or you have to calculate it. There are calibration methods available. You can also calculate it from manual measurements.
If you need to estimate it, you can just place a yard stick at a known distance, take a picture, measure its length in pixels, and use the previous equations to evaluate:
f[px] = length[px] * distance[m] / length[m]
If you knew the sensor's pixel pitch, let's say 1.40 µm/px, and the true focal distance (not 35mm-equivalent), let's say 4.38 mm, then f[px] = 4.38 mm / (1.40 µm/px) = 3128 px. Those values are roughly representative of smartphone cameras and some webcams.

Python multiplication, exponent yields different precision

I've got some Python code that I'd like to understand what's going on (see below). I've got the results of the calculations as well.
If I square radius by repeated multiplication I get a different result than if I square radius. If it were rounding, I'd expect a smaller gap between the two calculations. Can someone put me on the right path, please?
import math
diameter=float(input('Enter the diameter: '))
radius = diameter / 2.0
area_1 = math.pi * radius * radius
print ("The area is: ", area_1)
area_2 = math.pi * radius**2
print ("The area is: ", area_2)
=========================================================
Enter the diameter: 6.2
The area is: 30.19070540099791**3**
The area is: 30.19070540099791**7**
The difference comes from the different way both expressions were calculated:
math.pi * radius * radius was calculated as:
a. tmp = math.pi * radius
b. tmp * radius
math.pi * radius**2
a. tmp2 = radius**2
b. tmp2 * math.pi
Mathematically both are equivalent but not so when we are talking about finite precision of floating point types in a computer.
You can read more on the topic on Wikipedia or other sources. The field of numerical analysis (and numerical methods) deals mostly with these numerical rounding errors in the pursue of finding best algorithms for involved calculations.

Can't accurately calculate pi on Python

I am new member here and I'm gonna drive straight into this as I've spent my whole Sunday trying to get my head around it.
I'm new to Python, having previously learned coding on C++ to a basic-intermediate level (it was a 10-week university module).
I'm trying a couple of iterative techniques to calculate Pi but both are coming up slightly inaccurate and I'm not sure why.
The first method I was taught at university - I'm sure some of you have seen it done before.
x=0.0
y=0.0
incircle = 0.0
outcircle = 0.0
pi = 0.0
i = 0
while (i<100000):
x = random.uniform(-1,1)
y = random.uniform(-1,1)
if (x*x+y*y<=1):
incircle=incircle+1
else:
outcircle=outcircle+1
i=i+1
pi = (incircle/outcircle)
print pi
It's essentially a generator for random (x,y) co-ordinates on a plane from -1 to +1 on both axes. Then if x^2+y^2 <= 1, we know the point rests inside a circle of radius 1 within the box formed by the co-ordinate axes.
Depending on the position of the point, a counter increases for incircle or outcircle.
The value for pi is then the ratio of values inside and outside the circle. The co-ordinates are randomly generated so it should be an even spread.
However, even at very high iteration values, my result for Pi is always around the 3.65 mark.
The second method is another iteration which calculates the circumference of a polygon with increasing number of sides until the polygon is almost a circle, then, Pi=Circumference/diameter. (I sort of cheated because the coding has a math.cos(Pi) term so it looks like I'm using Pi to find Pi, but this is only because you can't easily use degrees to represent angles on Python). But even for high iterations the final result seems to end around 3.20, which again is wrong. The code is here:
S = 0.0
C = 0.0
L = 1.0
n = 2.0
k = 3.0
while (n<2000):
S = 2.0**k
L = L/(2.0*math.cos((math.pi)/(4.0*n)))
C = S*L
n=n+2.0
k=k+1.0
pi = C/math.sqrt(2.0)
print pi
I remember, when doing my C++ course, being told that the problem is a common one and it isn't due to the maths but because of something within the coding, however I can't remember exactly. It may be to do with the random number generation, or the limitations of using floating point numbers, or... anything really. It could even just be my mathematics...
Can anyone think what the issue is?
TL;DR: Trying to calculate Pi, I can get close to it but never very accurately, no matter how many iterations I do.
(Oh and another point - in the second code there's a line saying S=2.0**k. If I set 'n' to anything higher than 2000, the value for S becomes too big to handle and the code crashes. How can I fix this?)
Thanks!
The algorithm for your first version should look more like this:
from __future__ import division, print_function
import sys
if sys.version_info.major < 3:
range = xrange
import random
incircle = 0
n = 100000
for n in range(n):
x = random.random()
y = random.random()
if (x*x + y*y <= 1):
incircle += 1
pi = (incircle / n) * 4
print(pi)
Prints:
3.14699146991
This is closer. Increase n to get even closer to pi.
The algorithm takes into account only one quarter of the unit circle, i.e. with a radius of 1.
The formula for the area of a quarter circle is:
area_c = (pi * r **2) / 4
That for the area of the square containing this circle:
area_s = r **2
where r is the radius of the circle.
Now the ratio is:
area_c / area_s
substitute the equations above, re-arange and you get:
pi = 4 * (area_c / area_s)
Going Monte Carlo, just replace both areas by a very high number that represents them. Typically, the analogy of darts thrown randomly is used here.
For the first one, your calculation should be
pi = incircle/1000000*4 # 3.145376..
This is the number of points that landed inside of the circle over the number of total points (approximately 0.785671 on my run).
With a radius of 1 (random.uniform(-1,1)), the total area is 4, so if you multiple 4 by the ratio of points that landed inside of the circle, you get the correct answer.

Basic trigonometry isn't working correctly in python

For a bit of background, this is the game I'm trying to draw in an isometric style.
I'm just trying to get the correct calculations instead of doing it in a hacky way, but one part isn't working, and I'm not quite sure about the other part (I'll save that for another question later on).
So, forgetting the little squares inbetween, the board is made up of n lenels. I'd like to be able to calculate the coordinates for these so I can do further calculations on them, but the trig isn't working, and to the best of my knowledge (bear in mind I last did it years ago), it should be.
This is the simple code to draw the first square:
import turtle
import math
iso_angle = 20
grid_length = 100
turtle.right(iso_angle)
turtle.forward(grid_length)
turtle.right(180 - iso_angle * 2)
turtle.forward(grid_length)
turtle.right(iso_angle * 2)
turtle.forward(grid_length)
turtle.right(180 - iso_angle * 2)
turtle.forward(grid_length)
Using sohcahtoa, I thought I'd be able to calculate the width and height of the resulting square, since it's effectively made up of 4 triangles, and I can double the height of one of the triangles.
#s = o / h
#sin(iso_angle) = o / grid_length
#o = sin(iso_angle) * grid_length
height = 2 * sin(iso_angle) * grid_length
width = 2 * cos(iso_angle) * grid_length
However, when I move the turtle down by height, it doesn't fall on the edge of the square. It doesn't even move in a multiple of the distance of the edge, it just seems to end up some random distance. Swapping with width doesn't work either.
Where abouts am I going wrong with this?
As stated in the comments you need to convert to radians which can be done with the
math.radians()
function. So in practice you would end with something like
height = 2 * sin(math.radians(iso_angle)) * grid_length
width = 2 * cos(math.radians(iso_angle)) * grid_length
The cursor module (turtle) takes angles in degrees.
The sin() and cos() math functions take angles in radians. You must convert them. Fortunetly, Python includes convenient functions to do that in the math module:
height = 2 * sin(radians(iso_angle)) * grid_length
Hope this helps.

I need help forming a circle with cubes, useing blender 2.69 with python engine

Please forgive me, but I only really know how to somewhat code in VB, and python is not what I'm used to. I did try to see if other people have made and or shown an algorithm that I'm trying to accomplish.
I have a visualizer design in my head and What I have been trying to do is get a number of cubes (variable input for now) to be placed a certain distance (maybe 5-10 blender units) from the center of the scene and angle the faces so that there will be one face pointing to the center and one face pointing the opposite direction. I'm trying to just start with 10 cubes because I feel like it will be a fair number to hopefully show a circle shape.
I made an image to help describe what I am trying to do:
All I have been able to figure out so far is that I need to add a cube with a certain rotation, and that rotation needs to be stepped for each cube. so a small equation is needed, something like this.
(10) (36)
360 / numberOfCubes = steppedAngle
That's all I have been able to figure out because I don't know how to program python to do such.
Any help is greatly appreciated, and will be credited in the final render.
Update: 1
Thanks to the help from the answer below, I finally got it to work how i wanted.
img http://vvcap.net/db/bKKUz3Uw4WUqL_WVDU0j.png
and here is the code written in help from the answer below.
'
import bpy
import math
##num of cubes
n = 10
##distange from center
radius = 7
for i in range(1, n + 1):
angle = (i - 1) * math.pi * 2 / n
xcoord=(radius * math.cos(angle))
ycoord=(radius * math.sin(angle))
bpy.ops.mesh.primitive_cube_add(location=(xcoord,ycoord,0),rotation=(0,0,angle))
'
Let's start with cubes in a circle, and we will work our way from there.
You have N cubes, and you want to place them in a circle of radius R around the center of the universe (0,0,0).
Applying basic trigonometry:
Each cube is on one of the radius of the circle, when you divide the circle by N. Therefore, your first cube is at 0 rad, your second cube is at 2*pi/N rad, your third cube is at 2 * 360/N rad, ... your N cube is at (N-1) * 2*pi/N rad. Now we have a formula:
Location of the cube in the circle = (i - 1) * 2*pi/N in radians, for each i from 1 to N.
Now, the location in space coordinates is (r*cos(angle), r*sin(angle), 0) for a circle that is placed on the XY plane and it's center is on (0,0,0).
My Blender Python is very rusty, so I won't provide you a complete solution, but it should be this way:
import math
for i in range(1, N + 1):
angle = (i - 1) * math.pi * 2 / N
x_coord = radius * math.cos(angle)
y_coord = radius * math.sin(angle)
z_coord = 0
cube = place_cube(x_coord, y_coord, z_coord)
This will place the cubes on the right coordinates, but it won't turn them the right way. Fortunately, you can rotate each cube by angle, and get it in the right orientation. So you can do:
import math
for i in range(1, N + 1):
angle = (i - 1) * math.pi * 2 / N
x_coord = radius * math.cos(angle)
y_coord = radius * math.sin(angle)
z_coord = 0
cube = place_cube(x_coord, y_coord, z_coord)
cube.rotate_around_z(angle)
I have not provided the place_cube and rotate_around_z functions because I hardly remember the Blender Python api, but it shouldn't be too hard.

Categories