1

I have the following array:

propensity = [32.  0.  0.]

I've calculated the sum of the array as follows:

a0 = sum(propensity)

I'm trying to calculate a fraction for every element of the array over the sum of the array and have written the following function:

def prob_rxn_fires(propensity, a0):
for x in propensity:
    print("propensity:\n", x)  
    prob = x/a0  
print("Prob reaction fires:\n", prob)      
return prob

I want the function to return three fractions for each array element, at the moment it only returns 0. I think that's because when it iterates through the array and reaches the return statement it returns only the last value it computed which is 0/32 = 0.0. I need to return the first 2 values as well but am unsure how to fix this?

Cheers

0

2 Answers 2

1

What about using numpy?

import numpy as np

propensity = np.array([32.0,  0.0,  0.0])
propensity/sum(propensity)

Output:

array([1., 0., 0.])
Sign up to request clarification or add additional context in comments.

Comments

1

You can do simply as

propensity = [32.,  0.0,  0.0]
a0 = sum(propensity)
propensity = [x/a0 for x in propensity]
print(propensity)

Output

[1.0, 0.0, 0.0] 

3 Comments

This technique might run into low-level issues as the propensity iterable is being iterated and written in parallel. Consider revising.
What sort of low level issues ? ,I think only checkfor division by zero needs to be added , and also for your solution why to import numpy for such simple task
TBH I cannot remember all the details. From what I remember, when Python assigns an iterable to a hash table, sometimes the loop will not continue as it considers the next value as already seen, so exits prematurely - due to the order in which hash values are stored. Suggestion: Just assign your list comp output to another variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.