0% found this document useful (0 votes)
12 views9 pages

Programming

Mat lab

Uploaded by

sumantapenthoi44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

Programming

Mat lab

Uploaded by

sumantapenthoi44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

keyboard_arrow_down 1. Write a program to find the solutions of a Quadratic equation.

Quadratic equation of the form - ax2 + bx + c = 0

Discriminant: D = b
2
− 4ac

D > 0, the roots are real and distinct


D = 0, the roots are real and equal.
D < 0, the roots do not exist or the roots are imaginary.

2 2
−b+√ b −4ac −b−√ b −4ac
roots of the equation = 2a
, 2a

eg. x2 − 4x − 5 = 0

Where, a = 1, b = −4 and c = −5

a = int(input("Enter value for a:"))


b = int(input("Enter value for b:"))
c = int(input("Enter value for c:"))

D = (b**2) - (4*a*c)

if D >= 0:
x1 = (-b + D**0.5)/(2*a)
x2 = (-b - D**0.5)/(2*a)

print(f"The two roots of the quadratic equation are {x1} and {x2}.")
else:
print(f"The roots do not exist or the roots are imaginary.")

Enter value for a:1


Enter value for b:-4
Enter value for c:-5
The two roots of the quadratic equation are 5.0 and -1.0.

keyboard_arrow_down 2. Write a program to find the addition of two matrices.


# prompt: Create a python program to find the addition of two matrices.

import numpy as np

# Define the first matrix


matrix_1 = np.array([[1, 2, 3],
[4, 5, 6]])

# Define the second matrix


matrix_2 = np.array([[7, 8, 9],
[10, 11, 12]])

# Add the two matrices


matrix_sum = np.add(matrix_1, matrix_2)

# Print the resulting matrix


print("The sum of the two matrices is:")
print(matrix_sum)

The sum of the two matrices is:


[[ 8 10 12]
[14 16 18]]

keyboard_arrow_down 3. Write a program to find the Fibonacci series.


0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . . .

F0 = 0 F1 = 1

and

F n = F n−1 + F n−2 where, n > 1

num_terms = int(input("Enter number of Fibonacci terms:"))

Fibb = [0, 1]
if num_terms <= 2:
pass
else:
for n in range(2,num_terms):
Fibb.append(Fibb[n-1] + Fibb[n-2])
print(f"{n}: {Fibb}")

print(Fibb)

Enter number of Fibonacci terms:10


2: [0, 1, 1]
3: [0, 1, 1, 2]
4: [0, 1, 1, 2, 3]
5: [0, 1, 1, 2, 3, 5]
6: [0, 1, 1, 2, 3, 5, 8]
7: [0, 1, 1, 2, 3, 5, 8, 13]
8: [0, 1, 1, 2, 3, 5, 8, 13, 21]
9: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

keyboard_arrow_down 4. Write a program to find the GCD and LCM of two numbers.
num1 = int(input("Enter 1st number:"))
num2 = int(input("Enter 2nd number:"))

a, b = num1, num2

# Euclidean algorithm
while a != b:
if a > b:
a = a - b
else:
b = b - a
gcd = a

lcm = int(num1 * num2 / gcd)

print(f"GCD and LCM of {num1} and {num2} is {gcd} and {lcm} respectively.")

Enter 1st number:8


Enter 2nd number:12
GCD and LCM of 8 and 12 is 4 and 24 respectively.

keyboard_arrow_down 5. Write a program to test a number is prime or not.


We use trial division method.

number = int(input("Enter a number:"))

num_of_factors = 0

for factor in range(1,number + 1):


if number % factor == 0:
num_of_factors += 1
if num_of_factors > 2:
break
if num_of_factors > 2:
print(f"{number} is not a prime number.")
else:
print(f"{number} is a prime number.")

Enter a number:73
73 is a prime number.

keyboard_arrow_down 6. Write a program to find the transpose of a matrix.


# prompt: Create a python program to find the transpose of a matrix

import numpy as np
# Define the matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Find the transpose of the matrix


matrix_transpose = np.transpose(matrix)

# Print the resulting matrix


print("The transpose of the matrix is:")
print(matrix_transpose)

The transpose of the matrix is:


[[1 4 7]
[2 5 8]
[3 6 9]]

keyboard_arrow_down 7. Write a program to find the area of a circle.


2
area = πr

import math

radius = float(input("Enter radius:"))


area = math.pi * radius ** 2
print(f"The area of the circle with radius {radius} is {area:.2f}")

Enter radius:25
The area of the circle with radius 25.0 is 1963.50

keyboard_arrow_down 8. Write a program to find the area of an ellipse.


area = πab

Where, a is semi-major axis and b is semi-minor axis

semiMajor = float(input("Enter length of semi-major axis:"))


semiMinor = float(input("Enter length of semi-minor axis:"))

area = math.pi * semiMajor * semiMinor

print(f"The area of an ellipse with semi-major axis {semiMajor} and semi-minor axis {semiMinor} is {area:.2f}")

Enter length of semi-major axis:10


Enter length of semi-minor axis:12
The area of an ellipse with semi-major axis 10.0 and semi-minor axis 12.0 is 376.99

keyboard_arrow_down 9. Write a program to arrange some numbers in ascending order.


(Sorting)

num_terms = int(input("How many numbers? "))


num_list = []

for num in range(0,num_terms):


num_list.append(int(input("Enter number:")))

print(num_list)

for i in range(0,len(num_list)):
for j in range(i+1,len(num_list)):
if num_list[j] < num_list[i]:
temp = num_list[i]
num_list[i] = num_list[j]
num_list[j] = temp
print(num_list)

print(num_list)

How many numbers? 5


Enter number:5
Enter number:2
Enter number:7
Enter number:1
Enter number:4
[5, 2, 7, 1, 4]
[1, 5, 7, 2, 4]
[1, 2, 7, 5, 4]
[1, 2, 4, 7, 5]
[1, 2, 4, 5, 7]
[1, 2, 4, 5, 7]
[1, 2, 4, 5, 7]
keyboard_arrow_down 10. Write a program to multiply two matrices.
# prompt: Create a python program to multiply two matrices.

import numpy as np

# Define the first matrix


matrix_1 = np.array([[1, 2, 3],
[4, 5, 6]])

# Define the second matrix


matrix_2 = np.array([[7, 8],
[9, 10],
[11, 12]])

# Multiply the two matrices


matrix_product = np.matmul(matrix_1, matrix_2)

# Print the resulting matrix


print("The product of the two matrices is:")
print(matrix_product)

The product of the two matrices is:


[[ 58 64]
[139 154]]

keyboard_arrow_down 11. Write a program to find the sum of diagonal elements of a matrix.
# prompt: Create a python program to find the trace of a matrix.

import numpy as np

# Define the matrix


matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Find the trace of the matrix


trace = np.trace(matrix)

# Print the resulting trace


print("The trace of the matrix is:")
print(trace)

The trace of the matrix is:


15

keyboard_arrow_down 12. Write a program to find the Factorial of a number.


5! = 5 × 4 × 3 × 2 × 1 = 120

number = int(input("Enter a number:"))


factorial = 1

while number > 0:


factorial = factorial * number
number = number - 1
print(f"The factorial of the number is {factorial}.")

Enter a number:5
The factorial of the number is 120.

number = int(input("Enter a number:"))


factorial = 1
i = 1
while i <= number:
factorial = factorial * i
i = i + 1
print(f"{number}! = {factorial}")

Enter a number:5
5! = 120
keyboard_arrow_down 13. Write a program to find the Surface area of a sphere.
2
S urf ace Area = 4πr

radius = float(input("Enter radius of sphere:"))


surface_area = 4 * math.pi * radius ** 2

print(f"The surface area of sphere with radius {radius} is {surface_area:.2f}")

Enter radius of sphere:5


The surface area of sphere with radius 5.0 is 314.16

keyboard_arrow_down 14. Write a program to find the sum of digits of a number.


Suppose, number is 1234

sum of digits is 1 + 2 + 3 + 4 = 10

% - remainder operator

// - integer division

number = int(input("Enter a number:"))

sum_of_digits = 0

while number % 10 > 0:


digit = number % 10
number = number // 10
sum_of_digits = sum_of_digits + digit

print(f"The sum of digits is {sum_of_digits}")

Enter a number:7895
The sum of digits is 29

keyboard_arrow_down 15. Write a program to find the Volume of a Cone.


1 2
V olume of a cone = πr h
3

for For a circular cone with radius r and height h

radius = float(input("Enter radius of cone base:"))


height = float(input("Enter height of cone:"))

volume = math.pi * radius ** 2 * height / 3


print(f"The volume of a circular cone with radius {radius} and height {height} is {volume:.2f}")

Enter radius of cone base:4


Enter height of cone:4
The volume of a circular cone with radius 4.0 and height 4.0 is 67.02

keyboard_arrow_down 16. Write a program to find the Volume of a Sphere.


4 3
volume = πr
3

radius = float(input("Enter radius of sphere:"))


volume = (4/3) * math.pi * radius ** 3

print(f"The volume of a sphere with radius {radius} is {volume:.2f}")

Enter radius of sphere:5


The volume of a sphere with radius 5.0 is 523.60

keyboard_arrow_down 17. Write a program to check a number is a palindrome or not.


num = input("Enter a number:")
revnum = "".join(reversed(num))

if num == revnum:
print("Its a palindrome!")
else:
print("It's not a palindrome!")

Enter a number:1221
Its a palindrome!

keyboard_arrow_down 18. Write a program to find the Surface Area of a Prism


We will assume that that we are given - base area, base perimeter and height

surface area of prism formula = (2 × Base Area) + (Base perimeter × height)

base_area = float(input("Enter base area:"))


base_perimeter = float(input("Enter base perimeter:"))
height = float(input("Enter prism height:"))

area = (2 * base_area) + (base_perimeter * height)


print(f"The area of a prism with base area {base_area}, base perimeter{base_perimeter} and height {height} is {area}.")

Enter base area:4


Enter base perimeter:5
Enter prism height:6
The area of a prism with base area 4.0, base perimeter5.0 and height 6.0 is 38.0.

keyboard_arrow_down 19. Write a program to calculate the Product of two complex numbers.
(x + yi) (u + vi) = (xu − yv) + (xv + yu)i.

x = int(input("Enter (real) x:"))


y = int(input("Enter (Imz) y:"))
u = int(input("Enter (real) u:"))
v = int(input("Enter (Imz) v:"))

real = x * u - y * v
img = x * v + y * u

print(f"({x} + {y}i)({u} + {v}i) = ({real} + {img}i)")

Enter (real) x:4


Enter (Imz) y:5
Enter (real) u:2
Enter (Imz) v:3
(4 + 5i)(2 + 3i) = (-7 + 22i)

keyboard_arrow_down 20. Write a program to find the Exponential series.


# prompt: Create a python program to find the exponential series.

import math
import numpy as np

def exponential_series(x, n):


"""
Calculates the exponential series up to the nth term.

Args:
x: The value at which to evaluate the series.
n: The number of terms to include in the series.

Returns:
The value of the exponential series up to the nth term.
"""

# Initialize the sum to 0.


sum = 0.0

# Iterate over the terms of the series.


for i in range(n):
sum += x**i / math.factorial(i)

return sum

# Define the input value and number of terms.


x = 1.0
n = 10
# Calculate the exponential series.
result = exponential_series(x, n)

# Print the result.


print(f"The exponential series for x = {x} and n = {n} is: {result}")

The exponential series for x = 1.0 and n = 10 is: 2.7182815255731922

keyboard_arrow_down 21. Write a program to dispaly Pascal's Triangle.


# Function to print
# first n lines of
# Pascal's Triangle
def printPascal(n) :

# Iterate through every line


# and print entries in it
for line in range(0, n) :

# Every line has number of


# integers equal to line
# number
for i in range(0, line + 1) :
print(binomialCoeff(line, i),
" ", end = "")
print()

def binomialCoeff(n, k) :
res = 1
if (k > n - k) :
k = n - k
for i in range(0 , k) :
res = res * (n - i)
res = res // (i + 1)

return res

# Driver program
n = 8
printPascal(n)

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

keyboard_arrow_down 22. Write a program to find the Sine series and Cosine series.
# prompt: Create a python program to find the sine and cosine series

import math

def sine_series(x, n):


"""
Calculates the sine series up to the nth term.

Args:
x: The value at which to evaluate the series.
n: The number of terms to include in the series.

Returns:
The value of the sine series up to the nth term.
"""

# Initialize the sum to 0.


sum = 0.0

# Iterate over the terms of the series.


for i in range(n):
sum += ((-1)**i * x**(2*i + 1)) / math.factorial(2*i + 1)
return sum

def cosine_series(x, n):


"""
Calculates the cosine series up to the nth term.

Args:
x: The value at which to evaluate the series.
n: The number of terms to include in the series.

Returns:
The value of the cosine series up to the nth term.
"""

# Initialize the sum to 0.


sum = 0.0

# Iterate over the terms of the series.


for i in range(n):
sum += ((-1)**i * x**(2*i)) / math.factorial(2*i)

return sum

# Define the input value and number of terms.


x = math.pi / 3
n = 10

# Calculate the sine series and cosine series.


sine_result = sine_series(x, n)
cosine_result = cosine_series(x, n)

# Print the results.


print(f"The sine series for x = {x} and n = {n} is: {sine_result}")
print(f"The cosine series for x = {x} and n = {n} is: {cosine_result}")

The sine series for x = 1.0471975511965976 and n = 10 is: 0.8660254037844385


The cosine series for x = 1.0471975511965976 and n = 10 is: 0.5000000000000001

keyboard_arrow_down 23. Write a program to find all factors of a number.


number = int(input("Enter a number:"))

for factor in range(1,number + 1):


if number % factor == 0:
print(factor, end=" ")

Enter a number:20
1 2 4 5 10 20

keyboard_arrow_down 24. Write a program to generate a list of primes between 1 and n. Find the twin primes and
count no of primes of the form 4n+1 and 4n-3.

number = int(input("Enter a number:"))

list_of_primes = []
twin_primes = []

for num in range(1,number + 1):


num_of_factors = 0
for factor in range(1,num+1):
if num % factor == 0:
num_of_factors += 1
if num_of_factors > 2:
continue
list_of_primes.append(num)

for i in range(len(list_of_primes) - 1):


if list_of_primes[i] + 2 == list_of_primes[i+1]:
twin_primes.append((list_of_primes[i], list_of_primes[i+1] ))

print(f"List of primes between 1 and {number} is {list_of_primes}")


print(f"List of twin primes are - {twin_primes}")

Enter a number:10
List of primes between 1 and 10 is [1, 2, 3, 5, 7]
List of twin primes are - [(3, 5), (5, 7)]

You might also like