Sthln
Sthln

Reputation: 71

Recoding from C to Python

I'm pretty much a layman in C and I'm learning Python. I need to write the routine described below (in C) for Python:

#include <stdio.h>
#include <math.h>

main()
{
    float   hold[26], hnew[26];
    float   dt, dx;
    float   t, s;
    float   ho;
    float   time;
    float   f1, d2h;

    int i;
    int nx, nlx;
    int n, nend;
    int kount, kprint;


    dt  = 5.0;
    dx  = 10.0;
    t   = 0.02;
    s   = 0.002;
    nx  = 11;
    nlx = nx-1;


    ho = 16.0;
    for( i = 1;  i <= nx;  i++ )
    {
        hold[i] = ho;
        hnew[i] = ho;
    }

    hold[nx] = 11.0;

    printf("\t\t\t\thead\t\t\t\t      time\n\n");
    kount  = 1;
    kprint = 2;

    time = dt;
    nend = 100;


    for( n = 1;  n <= nend;  n++ )
    {
            /* update solution */

        for( i = 2;  i <= nlx;  i++ )
        {
            f1 = dt*t/s;
            d2h = ( hold[i+1] - 2.0*hold[i] + hold[i-1])/(dx*dx);
            hnew[i] = hold[i] + (f1*d2h);
        }

        for( i = 1;  i <= nlx;  i++ )
        {
            hold[i] = hnew[i];
        }


        if( kount == kprint )
        {
            for( i = 1;  i <= nx;  i++ )
            {
                printf(" %.2f",hold[i]);
            }
            printf("   %6.2f\n",time);
            kount = 0;
        }

        time  = time + dt;
        kount = kount + 1;
    }
}

This is my attempt at Python:

import numpy as np
dt = 5.0
dx = 10.0
t = 0.02
s = 0.002
nx = 11
nlx = nx - 1
ho = 16.0

hold = np.zeros(nx+1)
hnew = np.zeros(nx+1)

for i in range(nx):
    hold[i] = ho
    hnew[i] = ho

hold[nx] = 11.0

However, I can't get over this because I don't know the Python correspondent of the printf function. What would be the correct form of this function in Python? What does it reffer to?

Upvotes: 0

Views: 119

Answers (3)

Chris Charley
Chris Charley

Reputation: 6633

To print similar to C's printf, the following is an example:

f = 3.25645
g = 3.14159265358979

for fl in (f,g):
    print(f'{fl:.2f}')


3.26
3.14

The first f in the print is the format specifier. The f in the braces says to consider the number as a float.

Upvotes: 2

joep
joep

Reputation: 1

it just print() (see a small program below)

squares = []
for x in range(14):
 squares.append(x**2)

squares

squares2 = [x**2 for x in range(100)]

print (squares2) 

Upvotes: 0

tim
tim

Reputation: 901

Just print() in Python with .format.

For example:

x, y = 1, 2

print("x = {0}, y = {1}".format(x, y))

Here's the doc

Upvotes: 2

Related Questions