Back to Freecodecamp

Step 4

curriculum/challenges/english/blocks/learn-encapsulation-by-building-a-projectile-trajectory-calculator/660400f02cf3a76795b82d4e.md

latest2.4 KB
Original Source

--description--

The first thing to set up is a method that calculates the displacement of the projectile, which is the horizontal space traveled from the throw to when the projectile touches the ground.

Create a method __calculate_displacement, which has only self as a parameter, and return the displacement of the projectile.

Use the following formula to compute the projectile displacement: \[ d = \frac{v \cdot \cos\theta \cdot \left(v\cdot\sin\theta + \sqrt{v^2 \cdot \sin^2\theta + 2 \cdot g \cdot h}\right)}{g} \]

In which $d$ is the displacement, $v$ is the starting speed, $\theta$ is the angle and $h$ is the starting height of the projectile. For $g$ you can use the GRAVITATIONAL_ACCELERATION variable.

You should use the methods math.cos() and math.sin() for the trigonometric functions and math.sqrt() to calculate the square root. Also you should know that $x^y$ is written as x ** y in python. Also $\sin^2\theta$ means that the value resulting from the sine is then squared.

Remember that with name mangling you need to call the method as _Projectile__calculate_displacement if you want to test, or use it from outside of the class:

py
ball = Projectile(10, 3, 45)
displacement_of_ball = ball._Projectile__calculate_displacement() # 12.6173996009878

--hints--

You should declare a method called __calculate_displacement with def __calculate_displacement(self):.

js
({test: () => assert(runPython(`_Node(_code).find_class("Projectile").has_function("__calculate_displacement")`))})

The __calculate_displacement method should have only the self argument.

js
({test: () => assert(runPython(`_Node(_code).find_class("Projectile").find_function("__calculate_displacement").has_args('self')`))})

The __calculate_displacement method should return the correct value.

js
({test: () => assert(runPython(`
p = Projectile(20, 21, 22)
disp = p._Projectile__calculate_displacement()
round(disp, 2) == 55.06 and round(disp, 2) != disp
`))})

--seed--

--seed-contents--

py
import math

GRAVITATIONAL_ACCELERATION = 9.81
PROJECTILE = "∙"
x_axis_tick = "T"
y_axis_tick = "⊣"

class Projectile:
    __slots__ = ('__speed', '__height', '__angle')

    def __init__(self, speed, height, angle):
        self.__speed = speed
        self.__height = height
        self.__angle = math.radians(angle)
        
--fcc-editable-region--
    
--fcc-editable-region--