Category Archives: Programming

Demonstrating Newton’s laws of motion using Python code

Newton’s laws of motion are a set of three laws that describe the relationship between a body and the forces acting upon it. These laws were developed by Sir Isaac Newton in the 17th century and are still widely used in classical mechanics to describe the motion of objects.

Newton’s laws of motion provide a fundamental framework for understanding the motion of objects and the forces that act upon them.

Here is an example of how you could demonstrate Newton’s laws of motion using Python code:

Newton’s First law of motion with Python code

An object at rest tends to stay at rest, and an object in motion tends to stay in motion with the same speed and in the same direction, unless acted upon by a force.

# define a class to represent an object
class Object:
  def __init__(self, mass, velocity=0):
    self.mass = mass
    self.velocity = velocity
    
  def apply_force(self, force, time):
    # calculate the acceleration of the object
    acceleration = force / self.mass
    # update the velocity of the object based on the acceleration and time elapsed
    self.velocity += acceleration * time
    
# create an object with a mass of 10 kg and initial velocity of 0 m/s
obj = Object(10)
print("Initial velocity:", obj.velocity) # should print 0

# apply a force of 50 N for 1 second
obj.apply_force(50, 1)
print("Velocity after applying force:", obj.velocity) # should print 5 (50 N / 10 kg = 5 m/s^2)

# apply no force for 1 second
obj.apply_force(0, 1)
print("Velocity after applying no force:", obj.velocity) # should still print 5

Newton’s Second law of motion with Python code

Newton’s second law of motion states that the force acting on an object is equal to the mass of the object times its acceleration. In equation form, this is represented as:

F = ma

Where F is the force acting on the object, m is the mass of the object, and a is the acceleration of the object.

Python code that calculates the mass and acceleration of an object based on the given variables:

# Define the initial and final velocities of the object
initial_velocity = 10  # m/s
final_velocity = 20  # m/s

# Define the time elapsed
time_elapsed = 5  # s

# Calculate the change in velocity
delta_v = final_velocity - initial_velocity

# Calculate the acceleration of the object
acceleration = delta_v / time_elapsed

# Print the calculated acceleration
print("Acceleration:", acceleration, "m/s^2")

# Define the force acting on the object
force = 50  # N

# Calculate the mass of the object
mass = force / acceleration

# Print the calculated mass
print("Mass:", mass, "kg")

This code will output the following values:

  • Acceleration: 4 m/s^2
  • Mass: 12.5 kg

The variables initial_velocity, final_velocity, and time_elapsed can be changed to different values to calculate the acceleration and mass for different scenarios.

Now the below Python code demonstrates this principle by calculating the force required to accelerate a 1 kilogram object at a rate of 1 meter per second squared:

# Define the mass of the object in kilograms
mass = 1

# Define the acceleration of the object in meters per second squared
acceleration = 1

# Calculate the force required to accelerate the object
force = mass * acceleration

# Print the calculated force
print(force)

This code will output the result 1, which represents the force required to accelerate a 1 kilogram object at a rate of 1 meter per second squared.

Newton’s Third law of motion with Python code

For every action, there is an equal and opposite reaction.

import matplotlib.pyplot as plt
import numpy as np

# Constants
GRAVITY = 9.81  # m/s^2
MASS = 1.0      # kg

# Initial conditions
y_0 = 0         # m
v_0 = 10        # m/s
t_0 = 0         # s
dt = 0.01       # s

# Create lists to store the position and velocity of the ball at each time step
y_positions = [y_0]
v_velocities = [v_0]
times = [t_0]

# Loop through time steps and calculate the position and velocity of the ball at each step
while y_positions[-1] >= 0:
    # Calculate the acceleration of the ball due to gravity
    acceleration = -GRAVITY

    # Calculate the velocity at the current time step
    v_current = v_velocities[-1] + acceleration * dt

    # Calculate the position at the current time step
    y_current = y_positions[-1] + v_current * dt

    # Append the current position, velocity, and time to the lists
    y_positions.append(y_current)
    v_velocities.append(v_current)
    times.append(times[-1] + dt)

# Plot the position of the ball over time
plt.plot(times, y_positions)
plt.xlabel('Time (s)')
plt.ylabel('Position (m)')
plt.show()

This code simulates the motion of a ball being dropped from a height of y_0 meters with an initial velocity of v_0 meters per second. The ball is subjected to the force of gravity, which is represented by the acceleration GRAVITY meters per second squared. The code uses a while loop to step through the simulation, calculating the position and velocity of the ball at each time step using the equations of motion:

acceleration = force / mass
velocity = velocity + acceleration * dt
position = position + velocity * dt

At each time step, the ball experiences a force equal to its mass times the acceleration due to gravity (F = ma). This force is the action, and the reaction is the equal and opposite force that the ground exerts on the ball. The code plots the position of the ball over time, showing how it bounces back up after hitting the ground due to the equal and opposite reaction force.


Would you like to connect & have a talk?

My daily life involves interacting with different people in order to understand their perspectives on Climate Change, Technology, and Digital Transformation.

If you have a thought to share, then let’s connect!

Solving Euler’s formula for polyhedra, Navier-Stokes equations, and Feynman path integral using Python

Euler’s formula, the Navier-Stokes equations, and the Feynman path integral are three important concepts in the fields of mathematics and physics. Just to clarify, they are not a tall connected to one another directly, however, they are all related to our understanding of the world around us. We will be using the Python programming language to explore and solve these concepts. My assumption is that you understand all these formula’s and hence attempting to solve it using Python.

Euler’s formula is a tool that helps us understand the structure of three-dimensional shapes called polyhedra. It tells us the relationship between the number of vertices, edges, and faces that make up a polyhedron.

The Navier-Stokes equations, on the other hand, are used to study the movement of fluids. These equations are a set of mathematical statements that describe how fluids behave and are used to model the flow of liquids and gases in many different situations.

The Feynman path integral, named after physicist Richard Feynman, is a way of understanding the behavior of particles at the quantum level. It allows physicists to make predictions about the actions of particles by considering all of the possible paths they might take and calculating the chances of each one occurring.

Solving Euler’s formula for polyhedra using Python code

This is a Python function that checks if a three-dimensional shape, called a polyhedron, follows a certain rule called Euler’s formula. To use the function, you need to give it three whole numbers, which represent the number of flat faces, straight edges, and points on the polyhedron. The function will then tell you if the polyhedron follows Euler’s formula by giving you either ‘True’ or ‘False’:

def satisfies_euler(V, E, F):
  return V - E + F == 2
Continue reading Solving Euler’s formula for polyhedra, Navier-Stokes equations, and Feynman path integral using Python

Solving 5 mathematical Conjecture puzzles with Python code

There are many complex math puzzles that have stumped mathematicians and puzzle enthusiasts alike. Here are 5 mathematical conjecture puzzles that I have attempted to explain and solve using Python:

The Collatz Conjecture

The Collatz conjecture is a mathematical problem that involves a sequence of positive integers that are generated according to a specific rule. The conjecture states that for any positive integer, the sequence will eventually reach the number 1, regardless of the starting number.

Here is a simple Python function that generates the Collatz sequence for a given starting number:

def collatz(n):
    while n != 1:
        print(n, end=", ")
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3*n + 1
    print(1)

To use this function, you would simply call it with a positive integer as the argument, like this:

collatz(10)

This would output the following sequence:

10, 5, 16, 8, 4, 2, 1

The conjecture has been verified for many starting numbers, but it has not been proven for all positive integers. Despite much effort, a general proof or counterexample has not yet been found.

Continue reading Solving 5 mathematical Conjecture puzzles with Python code

Python code to assess carbon contribution on surface temperature

To calculate the contribution of carbon dioxide (CO2) to the current surface temperature of the Earth, we will need to use a combination of physical principles and data on atmospheric concentrations of CO2 and other greenhouse gases. In this article we will try and understand the basics of calculating the carbon concentration affecting the surface temperature using Python programming. But, before let’s do a general outline of the steps we can follow:

  1. Determine the current atmospheric concentrations of CO2 and other greenhouse gases. We can find this information from various sources, including scientific papers, government agencies, and online databases.
  2. Calculate the global mean surface temperature of the Earth. This can be done by using temperature data from a large number of locations around the globe and averaging them.
  3. Determine the amount of energy being absorbed by the Earth’s atmosphere from the sun. This can be calculated using the solar constant, which is the amount of solar energy received by the Earth per unit area per unit time, and the Earth’s albedo, which is the fraction of solar energy reflected by the Earth’s surface and atmosphere.
  4. Calculate the amount of energy being emitted by the Earth back into space. This can be done using the Stefan-Boltzmann law, which states that the rate at which a blackbody (such as the Earth) emits energy is proportional to the fourth power of its temperature.
  5. Calculate the difference between the energy absorbed by the Earth and the energy emitted back into space. This will give us the net energy balance of the Earth, which is the excess energy that is trapped in the Earth’s atmosphere.
  6. Determine the contribution of CO2 and other greenhouse gases to the net energy balance. This can be done by using the absorption and emission spectra of these gases, which describe how they absorb and emit energy at different wavelengths. We can then calculate the amount of energy absorbed and emitted by each gas and add them up to determine the total contribution of all the gases.
  7. Calculate the warming effect of the gases by comparing the net energy balance with and without the contribution of the gases. The difference between the two will give us the warming effect of the gases.

This is a simplified version of the process that scientists use to calculate the warming effect of greenhouse gases. In practice, the calculations are more complex and may involve using advanced computer models and data from a wide range of sources.

Continue reading Python code to assess carbon contribution on surface temperature

Indian Traditional mathematics equations in Python Code

Indian mathematics has a rich history dating back thousands of years. Some of the key contributions of traditional Indian mathematics include the development of the decimal place-value system and the concept of zero, as well as the development of various equations, trigonometry and algebra. In this article we will attempt to reproduce these equations using Python code.

The Pythagorean theorem

The Pythagorean theorem which states that in a right triangle, the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides:

a^2 + b^2 = c^2
Continue reading Indian Traditional mathematics equations in Python Code

High Level understanding of measuring wind speed with Python

In the following tutorial, you will learn how to use Python to infer wind speed based on anemometer data. Anemometers are devices that are used to measure wind speed and are connected to computers and other devices via USB connections. For instance, you can run a Python script to calculate the average wind speed over a given period of time. This is done by reading the anemometer data into a dataframe and then performing statistical calculations on the values.

Here is an example of how this could be done using Python:

import serial

# Open the serial port where the anemometer is connected
ser = serial.Serial('/dev/ttyUSB0', 9600)

# Read a line of data from the anemometer
line = ser.readline()

# Split the line into separate values
values = line.split(',')

# The wind speed is the first value in the list
wind_speed = float(values[0])

# Print the wind speed
print(wind_speed)

# Close the serial port
ser.close()

This code assumes that the anemometer is connected to a USB port on the computer and is sending data in the form of a comma-separated string. The wind speed is the first value in the string, and it is converted to a float so that it can be used in calculations.

Continue reading High Level understanding of measuring wind speed with Python

Python Password validator complying GDPR, ISO 27001/27002, PCI DSS, and NIST 800-53

There are several requirements that a password validator should meet in order to be compliant with various standards such as GDPR, ISO 27001/27002, PCI DSS, and NIST 800-53. Here are some general guidelines for creating a strong and compliant password:

  1. Length: A password should be at least 8 characters long. Some standards may require longer passwords, up to 12 or 16 characters.
  2. Complexity: A password should contain a mix of uppercase and lowercase letters, numbers, and special characters. Avoid using easily guessable information such as your name, address, or common words.
  3. Uniqueness: Each password should be unique and not used for any other accounts.
  4. Change frequency: It is recommended to change passwords at regular intervals, such as every 90 days or every year. Some standards may require more frequent changes.
  5. Storage: Passwords should be stored in a secure, encrypted format. They should not be written down or shared with anyone.
  6. Multi-factor authentication: It is recommended to use multi-factor authentication (MFA) in addition to a password, such as a code sent to your phone or a biometric factor like a fingerprint.
Continue reading Python Password validator complying GDPR, ISO 27001/27002, PCI DSS, and NIST 800-53

Setting up Python framework Django and no-sql database Cassandra for web development – Step by Step Tutorial

Setting up environment for God sake

Guys, I will be blunt. I am not teaching 100s of available ways to install Python, Django and Cassandra and to develop applications around it. My development environment is just defined below and everything is practiced around it. Because there are many ways to do things using these languages I have chosen the favorites that made me think is good for beginners to start with.

  • OS: UBUNTU 14.+ or 15.+
  • Python: 2.7
  • Level: Beginners Guide
  • Type: Getting Started
  • IDE: Brackets 1.5 (Experimenting with this one these days)
  • Environment: VirtualEnv 13.1.2
  • Framework: Django 1.8.6

 This content has been updated and tested with the versions defined above. I have been periodically updating the content to match the pace of new releases. 

Continue reading Setting up Python framework Django and no-sql database Cassandra for web development – Step by Step Tutorial

50 Python Libraries and Add-ons programmers cannot live without

There are plenty of Python libraries who really counts in projects and dramatically help-out programmers to reach a standard maturity level.

The list below is with my over all experience with python. I fond these 50 libraries to be basic for a programmer to use and build efficient applications. Many of these are now industry standards, and others are some nice geek stuffs. Just explore all of these and I am sure if you have these on your tips than you are among the best developers out there. And yeah you are fabulously costly priced 😀

Continue reading 50 Python Libraries and Add-ons programmers cannot live without

Python with Mathematics and Sequences – PART 2 & tricky cool Integer calculations

Here we will see some known and easy way of computing different mathematical and sequential things.

NOTE: This post is in continuation to the PART 1, however its not necessary to refer part I and you could take it as an independent post also.

Calculate the average of a series

# For an arbitrary sequence
def average(seq, total=0.0):
num = 0
for item in seq:
total += item
num += 1
return total / num

# For a sequence type such as a list or a tuple
def average(seq):
return float(sum(seq)) / len(seq)

Continue reading Python with Mathematics and Sequences – PART 2 & tricky cool Integer calculations