Matrice comme argument de fonction

Matrice comme argument de fonction

Alors j'avais déjà posé cette question il y'a 3 jours mais j'ai compris un truc depuis lors c'est que pour passer un ndarray comme argument d'une fonction, il faut soit ecrire A[][n] ou (*A)[n] mais maintenant j'ai un problème si vous pouviez m'aider s'il vous plait? pourquoi ça coince?

https://preview.redd.it/cke6z8yed4kh1.png?width=1920&format=png&auto=webp&s=a9bdc6dd5787aa951ee4100b8761f05312b59791

reddit.com
u/Mental_Primary_5558 — 2 days ago

I want to pass a matrix as a function argument

I want to pass a matrix as a function argument

int create_grid(int grid[][], int size){
    for(int i=0; i<size; i++){
        for(int j=0; j<size; j++){
            grid[i][j] = 0;
        }
    }

    return 0 ;
}

int main(){
    int size =128;
    int grid[size][size];

    return 0;
}

I'm getting error: "Array has incomplete element type 'int[ ]'

I don't understand I don't have that problem with 1d arrays

reddit.com
u/Mental_Primary_5558 — 5 days ago

je veux passer une matrice comme argument d'une fontion

je veux passer une matrice comme argument d'une fontion

int create_grid(int grid[][], int size){
    for(int i=0; i<size; i++){
        for(int j=0; j<size; j++){
            grid[i][j] = 0;
        }
    }

    return 0 ;
}

int main(){
    int size =128;
    int grid[size][size];

    return 0;
}

Mais j'obtiens: "Array has incomplete element type 'int[ ]'

j'ai pas ce probleme avec les 1d arrays

reddit.com
u/Mental_Primary_5558 — 5 days ago

I think I wanna be a Computational Scientist!!

So basically I'm a physics undergraduate student. I got into physics just by pure curiosity and love, I couldn't see my self doing something else than physics, but the problem was that my whole environment, and that includes parents, older sibling (actually two), my physics teacher in senior year high school, and my friends, all of them were like that's not a good option but I did it anyway.

They told me that theoretical physics don't matter anymore (cause that's all they thought about it I guess and me too and that's actually what got me in and by theoretical I mean just equations in a paper or on a board). It was two years ago and to be honest they were a bit right, I couldn't see any job perspective other that a teacher or a researcher (or both at a uni) and even though I was willing to go into research, they would also tell me that it was a super competitive with not much places available, and I kind of acknowledged that too but really I couldn't see my self studying anything else at uni so really plunged without thinking.

Now starting the last year my undergraduate (French system is 3y of undergrad) I think I found what I wanna do and that enthusiasts me while doing physics also. last year I had a numerical method course in fall semester, it was all python, and they taught us how to solve linear systems especially the Ax=b using LU decomposition, Gauss algorithm etc and how to solve numerically ODE (Euler & semi-Euler method, Verlet algorithm) and I was bad at it, I hated programming back then I didn't see any charm in it basically because I just couldn't understand it.

I got out with a 2/20 from that course (I didn't have a PC back then), then for Christmas break I had got a PC and dedicated all of my time just learning python basics (it's fun thinking Guido Von Rossum developed python during Christmas break he was alone), then I moved to the physics part, and though the linear system resolution didn't excite me much, the ODE resolution on the other hand completely blew my mind as I realized I could solve (approximate) non linear ODEs and especially that pendulum equation I knew since senior year high school that we only solved it for small angles completely and that blew my mind away, then I spent the following days solving all the ODEs I knew (from electricity to classical mechanics). for the resit exam I got the pendulum and smashed it then I really fell in love with physics programming as it also helped me grasp some details I missed in understanding them.

During the spring semester I enjoyed solving all my physics tutorials numerically (when there was a differential equation) but then one day I stumbled upon a Master degree on the internet presented my university and then I saw the light, a physics master that teaches you the computer in order to train computational scientist and physicist. I talked to a young teacher (as they are really nicer and have less responsibilities) if he could propose me an internship project and that's what he did he gave me DLA & KMC implementation and added a single constraint, no AI. I was cool with it. during that month I really helped me reinforce my new acquired abilities as I would be stuck with a single problem for hours, debugging the code and stuff. During that month I discovered Stack Overflow , stack exchange and reddit, I started asking questions and somehow, trying to explain my problem to others sometimes helped me find a solution to it and sometimes I would receive a response hours later and used that time in between trying to solve it (instead of just asking a LLM and getting dozens of lines of codes instantly).

Today I really enjoy learning programming, after the internship I started learning C++ and dived into the world of pointers, memory, and data structures.

In short, I see a real world use to my physics path now outside of academia and I'm really happy knowing that if one day I'm tired of research or don't have my place in it, I could go work as a computational scientist in the industry.

PS: I put the code I developed during my internship on GitHub but ashamed to show it to anybody, another constraint I had was to right the code only in functions and I really didn't knew how they worked fundamentally that means I could write and I wrote 700+ lines of code only in functions not knowing what I was doing (if that doesn't proof the existence of God 🙄️), A week after the internship I took a glance at it and I was ashamed as I declared every variable as global 😆️ I wonder what my tutor was thinking about when I presented that garbage.

Nonetheless the second part (KMC) was a bit better as I distinguished local from global variable but I didn't knew unpacking arguments when a function would return more that one variable.

That's my story from the day I stepped into physics at uni till today! I was more of a blog format, I'm happy if you enjoyed it, and excuse my English, I'm not a native!

reddit.com
u/Mental_Primary_5558 — 6 days ago

How to get my self all the way up to tree data structure

Hello guys, Im actually a physics undergrad student who's interested in computational physics and Im actually heading to a master in compuphys so I had this idea to make a solar system then after using a nested for loops I realised that it would cost problems when simulating a lot of bodies as it's complexity (the algorithm) is O(n²) I asked about technics to get past that and the answer I found was to implement an algorithm called Barnes-Hut that basically uses tree data structure. I figured out I needed some other concepts before that such as pointers structure enums Linked list,as I was learning c++ for the whole month of july ( basically just so that I could say I know two languages of programming) it turned out it was really going to be useful so I dived in to pointers (dereferences, arithmetics, pre post and pre incrementation). To my surprise I really seem to enjoy to learn about a language that teaches you about computer concept and not just about the program itself as would the python course I took at uni would do (afterall Im in physics so I don't complain) but now my question is what is the road or the milestones before getting to tree data structure. A high school friend of mine that took cs tells me that it's a whole semestre and I would have to go through pointers, struct and enums, pile & file, linked lists, double Linked lists (I don't know if that's how we call it in English sorry).

Is that pretty much it, are there missing stuffs, can you guys give me a propre road map, thank you.

reddit.com
u/Mental_Primary_5558 — 12 days ago

My files disappeared from my Linux home directory after shutting down the computer and turning it on the next morning

I believe the last command I ran yesterday evening was:

rm -rf ~/.vscode/extensions/extensions/ms-*

After running it, I noticed that all of my files, as well as my shell command history from before that point, are gone. Is there any way to recover the deleted files or restore the previous state of my home directory? Or has the data been permanently deleted? I'd also appreciate any guidance on what I should avoid doing right now to maximize the chances of recovery.

reddit.com
u/Mental_Primary_5558 — 12 days ago

Can we all agree that C/C++ have no for loops like Python does, since there is a boolean expression in the so-called "for loop" (and it could go infinite), whereas in Python we iterate over a range instead? 😁️ have a nice day!

reddit.com
u/Mental_Primary_5558 — 13 days ago

I'm surprised it worked!!

I wrote this very basic algorithm:

#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}

and I'm surprised, an int function took a double variable with no problem, or is there something under the hood,

reddit.com
u/Mental_Primary_5558 — 15 days ago

can I send a message N times automatically using Python

can I send a message N times automatically using Python? short question!

edit: guys listen I found out a way to do that with PyAutoGUI here is the code:

import PyAutoGUI

import time

message="You enter the text" # or make an input

number_of_message= 4 #just an exemple you can also make an input

time.sleep(10) # let yourself 10 seconds to put the cursor where you wanna print those messages, for me it was my Web whatsapp tab

for i in range(number_of_message):

PyAutoGUI.write(message)# it writes #automatically the message where your #cursor is at

PyAutoGUI.press("Enter")#it sends the #message automatically

time.sleep(2) # it lets a time interval #of two seconds between the messages

But it won't let me use my computer normally I cant move the cursor and have to wait till all the messages are sent, if you could also help me automate (make it automatic, sorry for my english) that it will be great!

reddit.com
u/Mental_Primary_5558 — 29 days ago

is it possible to speed up the execution of a for loop using Numba without wrapping it aroud a function

I wanna speed up the following code:

import numpy as np
import matplotlib.pyplot as plt

x_sun, y_sun, vx_sun, vy_sun, ax_sun, ay_sun,m_sun= 0,0,0,0,0,0,1

G=4*(np.pi)**2

x=[1, 0.72, 1.5237, 5.2, 0.47, 9.36, 19.18,30.1]

xpos=[[],[],[],[],[],[],[],[]]

y=[0, 0, 0, 0, 0, 0, 0, 0]

ypos=[[],[],[],[],[],[],[],[]]

vx=[0, 0, 0, 0, 0, 0, 0, 0]

vy=[6.281991687112502, 7.38, 5.0867271316753815, 2.74, 9.95, 2.04, 1.26, 1.145] 

ax=[0, 0, 0, 0, 0, 0, 0, 0]

ay=[0, 0, 0, 0, 0, 0, 0, 0]

mass=[
3.002513826043238e-06,
0.000002447,
3.2267471091000503e-07,
0.00050278543100000007166,
1.65e-07,
2.86e-04,
4.36e-05,
5.15e-05
]

dt=0.001

for i in range(10**4):
    for j in range(len(x)):
        # if x[j]>35 or y[j]>35:
        #     break
        # else:
        ax[j]=-G*(m_sun+mass[j])*x[j]/((x[j]**2+y[j]**2)**0.5)**3
        terme=0
        for k in range(len(x)):
            if k!=j:
                terme+=G*mass[k]*(x[k]-x[j])/(((x[k]-x[j])**2+(y[k]-y[j])**2)**0.5)**3
            else:
                continue
        ax[j]+=terme
        ay[j]=-G*(m_sun+mass[j])*y[j]/((x[j]**2+y[j]**2)**0.5)**3
        terme2=0
        for k in range(len(x)):
            if k!=j:
                terme2+=G*mass[k]*(y[k]-y[j])/(((x[k]-x[j])**2+(y[k]-y[j])**2)**0.5)**3
            else:
                continue
        ay[j]+=terme2 
        
        vx[j]+=ax[j]*dt
        vy[j]+=ay[j]*dt

        xpos[j].append(x[j])
        ypos[j].append(y[j])

        x[j]+=vx[j]*dt
        y[j]+=vy[j]*dt

I would like to know whether it is possible to speed up the execution of a for loop using Numba without first wrapping the loop inside a separate function. From what I understand, Numba is typically applied as a decorator (such as u/njit) to functions, but I was wondering if there is any way to compile or accelerate a standalone for loop directly, without having to refactor my code into a dedicated function. If this is not possible, I would also appreciate an explanation of why Numba requires functions in order to optimize Python code.

reddit.com
u/Mental_Primary_5558 — 29 days ago
▲ 0 r/cprogramming+1 crossposts

C++ question

Do you guys know a way of writting a code that outputs that:

Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40

it is the first part of a program that demands to calculate the max and min of an array, here is the whole thing:

Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40

Maximum element is: 90
Minimum element is: 10

I've been able to do the second part quite easily, here is what I proposed:

#include <iostream>


int main(){


    int arr[5]={10,20,30,40,50};
    int minimum=arr[0];
    int maximum=arr[0];
    for(int i=0; i<sizeof(arr)/sizeof(int);i++){
        if (minimum>arr[i]){
            minimum=arr[i];
        }
        if(maximum<arr[i]){
            maximum=arr[i];
        }
    }
    std::cout<<"le max= "<< maximum<<'\n';
    std::cout<<"le min= "<< minimum<<'\n';


    return 0;
}

but the list is created within the code.

reddit.com
u/Mental_Primary_5558 — 1 month ago

What's the difference between a function and an equation

Hi, a physics student here, can someone tell me what's the fundamental difference between a function and an equation, like why do we say the equation of a circle and not just the function that satisfies the following equation y^(2)=r^(2)+x^(2), if we take the center of the circle at the point C =(0,0)! thanks!!

reddit.com
u/Mental_Primary_5558 — 1 month ago

std::cin dans une boucle for, langage C++

Bonjour !

Quelqu'un pourrait-il m'expliquer comment fonctionne le code ci-dessous ?

```cpp
int main()
{
    double a = 0;
    for (std::cin >> a; a >= 0;std::cin >> a) {
        std::cout << "\t "<<a<<"\n";
    }
    return 0;
}

Je l'ai trouvé ici : https://stackoverflow.com/questions/41753771/using-cin-in-for-loop-defiition.

À l'origine, je voulais savoir s'il était possible d'utiliser std::cin directement dans une boucle for en C++. Le code fonctionne, mais je ne suis pas sûr de bien le comprendre, et donc je ne me sens pas capable de le modifier à ma guise.

En particulier, je ne comprends pas cette partie :

(std::cin >> a; a >= 0; std::cin >> a)

Si j'ai bien compris, std::cin >> a est d'abord exécuté pour initialiser la boucle. Ensuite, la condition a >= 0 est évaluée avec la valeur que l'utilisateur vient de saisir. Est-ce bien ça ?

J'ai aussi une autre question : il semble que le "\t" n'est pas simplement un caractère choisi au hasard. Si je le remplace, par exemple, par P, le code ne fonctionne plus comme prévu. Pourquoi ?

sinon voila le code que moi j'avais fait avant d'aller sur stackoverflow:

#include <iostream>


int main(){
    int arr[5];
    for(int i=1; i<=5; i++){
        std::cout<<"entre l'element: "<< i<<'\n';
        std::cin, arr[i];
    }


    return 0;
}
u/Mental_Primary_5558 — 1 month ago

Why does the Euler method give different results when using NumPy arrays instead of Python lists?

Can someone please tell me why these two codes don't give the same answer?

First code

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

G = 4 * (np.pi)**2
M_sun = 1  # solar mass
distance = 1  # AU
temps = 1  # year
M_earth = 3.002513826043238e-06  # solar mass
v_earth = 2 * np.pi  # AU/year
dt = 0.1
n_steps = 10**3

xpos = []
ypos = []

x_earth = 1.5
y_earth = 0

vx_earth = 0
vy_earth = v_earth

for i in range(n_steps):
    ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3
    ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3

    vx_earth = vx_earth + ax_earth * dt
    vy_earth = vy_earth + ay_earth * dt

    xpos.append(x_earth)
    ypos.append(y_earth)

    x_earth = x_earth + vx_earth * dt
    y_earth = y_earth + vy_earth * dt

plt.plot(xpos, ypos, color="green")
plt.show()

Second code

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

G = 4 * (np.pi)**2
M_sun = 1  # solar mass
distance = 1  # AU
temps = 1  # year
M_earth = 3.002513826043238e-06  # solar mass
v_earth = 2 * np.pi  # AU/year
dt = 0.1
n_steps = 10**3

x_earth = np.zeros(n_steps)
y_earth = np.zeros(n_steps)

vx_earth = np.zeros(n_steps)
vy_earth = np.zeros(n_steps)

x_earth[0] = 1.5
vy_earth[0] = v_earth

for i in range(n_steps - 1):
    ax_earth = -(G * M_sun) * x_earth[i] / ((x_earth[i]**2 + y_earth[i]**2)**0.5)**3
    ay_earth = -(G * M_sun) * y_earth[i] / ((x_earth[i]**2 + y_earth[i]**2)**0.5)**3

    vx_earth[i + 1] = vx_earth[i] + ax_earth * dt
    vy_earth[i + 1] = vy_earth[i] + ay_earth * dt

    x_earth[i + 1] = x_earth[i] + vx_earth[i] * dt
    y_earth[i + 1] = y_earth[i] + vy_earth[i] * dt

plt.plot(x_earth, y_earth, color="green")
plt.show()

The two implementations seem equivalent to me, except that the first stores the trajectory in Python lists while the second stores it in NumPy arrays. However, they produce different trajectories.

What am I missing?

PS: the close orbit is with the list method!!

reddit.com
u/Mental_Primary_5558 — 1 month ago

fonction python return selon certaines conditions

bonjour tout le monde, j'aimerais executer un code dont la logique est exactement la même:

import numpy as np

limport numpy as np

l=[0,1]

def albert():

p=np.random.choice(l)

if p==0:

name='einstein'

else:

name2='camus'

return (name or name2)

albert()

https://preview.redd.it/odlbduaf6t9h1.png?width=1920&format=png&auto=webp&s=ba1eeafea6b98d17e36c42f2b11c0636503225c0

name n'a aucun problème pour afficher einstein mais pour name2 il ne s'affiche jamais j'ai juste une erreur sur name " UnboundLocalError: cannot access local variable 'name' where it is not associated with a value "

quelqu'un à t-il la solution

reddit.com
u/Mental_Primary_5558 — 2 months ago

Question about the box-counting method to approximate the fractale dimension

Hi guys, I'm a physics student, I don't know much of maths concerning topology, metric spaces etc a part from basic linear algebra (Matrix diagonalization) so don't go to far with your explanation to my question!

I'm currently working on a project (diffusion limited agregation) where we get some fractal trees at the end of the simulation and in order to calculate its dimension I use the Box-Counting method, but why does it actually work? I mean like Hausdorff dimension is based on a definition, "dimension is related to how much the objet scales itself, as N^d=r" but what is the box_counting based on?

reddit.com
u/Mental_Primary_5558 — 2 months ago

Question sur Python #ndarray #np.where()

j'ai une liste L d'une certaine longeurs (3275 en l'occurence) qui contient des valeurs entre 0 et 4. j'ai voulu prendre toutes les valeurs=2 en faisant:

d=np.where(L==2)

j'ai le message d'erreur suivant: ValueError: Calling nonzero on 0d arrays is not allowed. Use np.atleast_1d(scalar).nonzero() instead. If the context of this error is of the form `arr[nonzero(cond)]`, just use `arr[cond]`.

pouvez vous me dire comment contourner ce problème et si possible d'ou vient-il?

PS: je mettrai un flair résolu si jamais je trouve une solution entre temps, merci de bien vouloir y répondre

reddit.com
u/Mental_Primary_5558 — 2 months ago

Python Tuple Sum

Hi guys, is it possible to add two tuples? For example, (x,y)+(a,b) such that the sum is (x+a, y+b) and not a concatenation (x,y,a,b). Thanks for your help.
reddit.com
u/Mental_Primary_5558 — 2 months ago