Python Forum
Write a program in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write a program in python
#1
Question 
Write a program in python that, based on the entered argument value,
calculates the value of a function specified as a graph.
Sorry for my bad English. Function for writing a program on a photo.

Description of the algorithm:
1. Enter the value of argument x and convert it to float.
2. Determine to which interval from the domain of definition of the function it
belongs, and calculate the value of the function y from the corresponding
formula.
3. Print the value of x and y.

Description of input and output data:
Input data comes from the keyboard, and output data is output to
monitor for viewing. The input and output data are of type float.

Program listing (option 1):
from math import * # now you can do this:
                            # print(sin(pi/4))
x = float(input('Enter value x='))
if x < -5: y = 1
if x >=-5 and x<0: y = -(3/5)*x-2

if x >= 0 and x<2: y = -sqrt(4-x**2)
if x >= 2 and x<4: y = x-2
if x >= 4 and x<8: y = 2+sqrt(4-(x-6)**2)
if x >= 8: y = 2
print("X={0:.2f} Y={1:.2f}".format(x, y))
It should be noted that in this recording of the algorithm the check is performed
for all conditional statements, including those following
calculated. So, for example, if x is -3, then the second one will be executed
operator, but in all subsequent operators the comparison operation will be
carried out. The number of checks can be reduced by writing a program with
using nested conditional statements.

Program listing (option 2):
from math import * # now you can do this:
                            # print sin(pi/4)
x = float(input('Enter value x='))
if x < -5:
y = 1
elif x >=-5 and x<0:
y = -(3/5)*x-2
elif x >= 0 and x<2:
y = -sqrt(4-x**2)
elif x >= 2 and x<4:
y=x-2
elif x >= 4 and x<8:
y = 2+sqrt(4-(x-6)**2)
else: y = 2
print("X={0:.2f} Y={1:.2f}".format(x, y))
Result of the program:
Enter the argument value: -6
X= -6.00 Y= 1
Enter the argument value: -3.33
X= -3.33 Y= -0.00
Enter argument value: 6
X= 6.00 Y= 4.00
buran write Oct-08-2023, 04:51 PM:
Please, use proper tags when post code, traceback, output, etc.
See BBcode help for more info.

Attached Files

Thumbnail(s)
   
Reply
#2
What exactly is the question?

This is a simple function to plot 3 simple graphs.

Read about mathplotlib and numpy! Plot all kinds of crazy things!

def myApp():
    import matplotlib.pyplot as plt
    import numpy as np

    x = np.linspace(0, 2, 100)

    fig, ax = plt.subplots()
    
    # these are the X values: [1, 2, 3, 4], these are the Y values [1, 4, 2, 3]
    ax.plot(x, x, label='linear')  # Plot some data on the axes.
    ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
    ax.plot(x, x**3, label='cubic')  # ... and some more.

    # if you don't set the ranges, the range shown will be a little more than the maximum value
    ax.set_xlim(0, 10)  # set the X range
    ax.set_ylim(0, 10)  # set the Y range
    
    ax.set_xlabel('my X axis')
    ax.set_ylabel('my Y label')
    ax.set_title('Linear, Quadratic and Cubic Plot')
    ax.legend()  # Add a legend.
    ax.grid(True)

    plt.show()
Reply
#3
(Oct-08-2023, 05:01 PM)Pedroski55 Wrote: What exactly is the question?

This is a simple function to plot 3 simple graphs.

Read about mathplotlib and numpy! Plot all kinds of crazy things!

def myApp():
    import matplotlib.pyplot as plt
    import numpy as np

    x = np.linspace(0, 2, 100)

    fig, ax = plt.subplots()
    
    # these are the X values: [1, 2, 3, 4], these are the Y values [1, 4, 2, 3]
    ax.plot(x, x, label='linear')  # Plot some data on the axes.
    ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
    ax.plot(x, x**3, label='cubic')  # ... and some more.

    # if you don't set the ranges, the range shown will be a little more than the maximum value
    ax.set_xlim(0, 10)  # set the X range
    ax.set_ylim(0, 10)  # set the Y range
    
    ax.set_xlabel('my X axis')
    ax.set_ylabel('my Y label')
    ax.set_title('Linear, Quadratic and Cubic Plot')
    ax.legend()  # Add a legend.
    ax.grid(True)

    plt.show()

"Write a program in python that, based on the entered argument value,
calculates the value of a function specified as a graph." This is a question or, more precisely, a task. I need to find the equations of the function and then to write a program based on the function. I already wrote it but I don’t know if it’s correct or not. Anyway thanks for help!!

from math import sqrt
 
x = float(input('x = '))
if x < -3:
   y = 3
elif x < 3:
     y = 3 - sqrt(3*3 - x*x)
elif x < 6:
     y = 9 - 2*x
else:
     y = x - 9
print(f'x = {x}, y = {y}'.format(x, y))
Reply
#4
(Oct-08-2023, 05:01 PM)Pedroski55 Wrote: Read about mathplotlib and numpy! Plot all kinds of crazy things!

And thank you a lot for this information!!
Reply
#5
I am not an expert, but I can do this if it helps. I never really need this stuff!

First make 1 numpy array of x values, then calculate corresponding y values.

Then you can plot x,y values with plt.plot(x_values, y_values, label='My label').

import matplotlib.pyplot as plt
import numpy as np

# create a numpy array of x values from -5 to 7
x_values = np.linspace(-5, 7, 100)
# create a list of y values from the x values
y_values = []
for i in x_values:    
    if i < -3:
       y = 3
    elif i < 3:
         y = 3 - np.sqrt(9 - i*i)
    elif i < 6:
         y = 9 - 2*i
    else:
         y = i - 9    
    y_values.append(y)

def drawIt():
    fig, ax = plt.subplots()
    ax.set_xlabel('my X axis')
    ax.set_ylabel('my Y label')
    ax.set_title('Ups and downs')
    plt.plot(x_values, y_values, label='My label')
    ax.grid(True)
    plt.show()
Just run drawIt() when you have made x_values and y_values!
Reply
#6
(Oct-09-2023, 06:40 AM)Pedroski55 Wrote: I am not an expert, but I can do this if it helps. I never really need this stuff!

First make 1 numpy array of x values, then calculate corresponding y values.

Then you can plot x,y values with plt.plot(x_values, y_values, label='My label').

import matplotlib.pyplot as plt
import numpy as np

# create a numpy array of x values from -5 to 7
x_values = np.linspace(-5, 7, 100)
# create a list of y values from the x values
y_values = []
for i in x_values:    
    if i < -3:
       y = 3
    elif i < 3:
         y = 3 - np.sqrt(9 - i*i)
    elif i < 6:
         y = 9 - 2*i
    else:
         y = i - 9    
    y_values.append(y)

def drawIt():
    fig, ax = plt.subplots()
    ax.set_xlabel('my X axis')
    ax.set_ylabel('my Y label')
    ax.set_title('Ups and downs')
    plt.plot(x_values, y_values, label='My label')
    ax.grid(True)
    plt.show()
Just run drawIt() when you have made x_values and y_values!

Thank you!!!! Heart
Reply
#7
You should write a function to stand-in as your function.
def f(x):
    if x < -3:
        return 3
    if x < 3:
        return 3 - (9 - x ** 2) ** 0.5
    if x < 6:
        return 9 - 2 * x
    return x - 9
This function is fairly easy to design. From the picture, your function is divided into 4 regions:
x < -3
-3 <= x < 3
3 <= x < 6
x >= 6

Most of the regions are straight lines and can be defined using y = mx + b where m is the slope (dy/dx) and b is the value of y at x = 0.

For the region x < 3
m= dy / dx = 0 / 4 = 0. b = y0 - m * x0 = 3 - (0 * -3) = 3
fx = 0x + 3 = 3

For the region 3 < x < 6
m = dy / dx = -6 / 3 = -2. b = y0 - m * x0 = 3 - (-2 * 3) = 9
fx = -2x + 9

for the region x >= 6
m = dy / dx = 5 / 5 = 1. b = y0 - m * x0 = -3 - (1 * 6) = -9
fx = x - 9

The range -3 <= x < 3 is a bit trickier. Here the points are on the circumference of a circle. For points on a circle centered at 0, 0 y = +/-sqrt(r^2 - x^2). We want the lower half of the circle, so the equation is y = -sqrt(r^2 - x^2). The equation can be transposed along the y axis by adding the y offset, and along the x axis by subtracting the x offset.
y = -sqrt(r^2 - (x - x0)^2) + y0 = sqrt(3^2 - (x - 0)^2) + 3 = sqrt(9 - x^2) + 3
fx = -(9 - x ** 2) **0.5 + 3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo How can I write a Python program for this structogram? rauljp9483 6 64,976 Nov-24-2021, 06:57 AM
Last Post: buran
  [split] Please advise how to write this program Rmasson 4 3,193 Apr-20-2019, 01:53 AM
Last Post: Skaperen
  Write a program to compute the sum of the terms of the series: 4 - 8 + 12 - 16 + 20 - chewey777 0 2,840 Mar-24-2018, 12:39 AM
Last Post: chewey777
  given 2 base 20 numbers write a program to subtract second from the first and return dp_tisha 2 3,794 Jul-06-2017, 09:22 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020